Questions tagged [smart-pointers]

An abstract data type that simulates a pointer while providing additional features, such as automatic garbage collection or bounds checking

Smart pointers are objects that look and feel like pointers, but are smarter.

What does this mean? To look and feel like pointers, smart pointers need to have the same interface that pointers do: they need to support pointer operations like dereferencing (operator *) and indirection (operator ->). An object that looks and feels like something else is called a proxy object, or just proxy. The proxy pattern and its many uses are described in the books Design Patterns and Pattern Oriented Software Architecture.

To be smarter than regular pointers, smart pointers need to do things that regular pointers don't. What could these things be? Probably the most common bugs in C++ (and C) are related to pointers and memory management: dangling pointers, memory leaks, allocation failures and other joys. Having a smart pointer take care of these things can save a lot of aspirin...

The simplest example of a smart pointer is auto_ptr, which is included in the standard C++ library (C++03). You can find it in the header <memory>, or take a look at Scott Meyers' auto_ptr implementation. Here is the relevant parts of auto_ptr's implementation, to illustrate what it does:

template <class T> class auto_ptr
{
    T* ptr;
public:
    explicit auto_ptr(T* p = 0) : ptr(p) {}
    ~auto_ptr()                 {delete ptr;}
    T& operator*()              {return *ptr;}
    T* operator->()             {return ptr;}
    // ...
};

As shown, auto_ptr is a simple wrapper around a regular pointer. It forwards all meaningful operations to this pointer (dereferencing and indirection). Its "smartness" is in the destructor: the destructor takes care of deleting the pointer.

For the user of auto_ptr, this means that instead of writing:

void foo()
{
    MyClass* p(new MyClass);
    p->DoSomething();
    delete p;
}

You can write:

void foo()
{
    auto_ptr<MyClass> p(new MyClass);
    p->DoSomething();
}

And trust p to clean-up after itself.

Smart pointers form part of the idiomatic RAII (Resource Acquisition Is Initialisation) technique that is core to resource management in C++.

Links:

http://ootips.org/yonat/4dev/smart-pointers.html

2763 questions
1
vote
1 answer

Mock a function throw an exception but Actual function call count doesn't match EXPECT_CALL

I want to mock the following method Ctrl::Do(const Handler& handler) to throw an exception. Ctrl stores a weak pointer to Handler class Ctrl { std::weak_ptr _handler; // ... }; And a reference of which gets passed to…
xyf
  • 664
  • 1
  • 6
  • 16
1
vote
0 answers

Using unique_ptr with custom deleter for arrays

I am using a C framework (DPDK) which provides its own memory management facilities. Now I want to encapsulate these special pointers in an unique_ptr, which requires using a custom deleter (invoking the de-allocation function of the framework). To…
1
vote
1 answer

Return a shared pointer from a function vs Capturing a shared pointer in a Lambda

I am constructing a shared pointer in a function_1 and giving it as a capture to a lambda. I think this is an issue, could you please confirm if this safe or I am right and I shoudn't be doing this? #include #include #include…
Vero
  • 313
  • 2
  • 9
1
vote
0 answers

Implementation of unique_ptr

I'm trying to understand how unique_ptr works inside. I found a simple implementation. Please tell me what the constructor does. template> class unique_ptr { public: using pointer = T*; using…
JDbP
  • 53
  • 4
1
vote
2 answers

Having troubles with smart pointers and vectors, constant crashing

So im trying to build a merkle tree from a vector of strings, first convert all the strings to the MerkleNodes and then form their parents, building the tree upside down. But it seems to be an issue when i push all the nodes to the vector in the…
1
vote
1 answer

gtest if an instance method is called from another class instance through a smart pointer to it?

Suppose I have a class class MinorClass{ virtual void NestedFunction(){...}; }; that is used to as following in another class class MajorClass{ public: MajorClass(unique_ptr&& input) : minor_class{std::move(input)}{}; …
roschach
  • 8,390
  • 14
  • 74
  • 124
1
vote
2 answers

no known conversion from 'std::shared_ptr' to 'int *' for 1st argument

when operating smart pointers, something confused me. Hers is the error message no known conversion from 'std::shared_ptr' to 'int *' for 1st argument and here's the code I ran #include #include class test { public: int…
1
vote
1 answer

State of underlying resource when a shared_ptr is created from the raw pointer?

This link about shared pointers states that You can pass a shared_ptr to another function in the following ways: ... Pass the underlying pointer or a reference to the underlying object. This enables the callee to use the object, but doesn't enable…
yokus
  • 145
  • 2
  • 10
1
vote
1 answer

What is the best way to resolve mutable borrow after immutable borrow, IF there is no perceived reference conflict

This question popped into my head (while I wasn't programming), and it actually made me question a lot of things about programming (like in C++, C#, Rust, in particular). I want to point out, I'm aware there is a similar question on this…
Andrew900460
  • 621
  • 1
  • 6
  • 16
1
vote
1 answer

Why does the pointer exist even after the unique_ptr to which the pointer is assigned goes out of scope?

I recently started learning about smart pointers and move semantics in C++. But I can't figure out why this code works. I have such code: #include #include using namespace std; class Test { public: Test() { …
1
vote
3 answers

How to Initialize a Map of Unique pointer Objects sorted by a Object Variable

Hello I am new to the c++ and have a problem with a Unique Pointer of a Object as a Key of a Map. What does the template need to look like on std::map,string,?> phonebookMap2; so the Person gets Sorted/Inserted initial by…
Rokrait
  • 31
  • 5
1
vote
1 answer

How to implement cast for "smart pointer" non-const to const

I am attempting to understand the internals of std::shared_ptr by writing my own (VERY BASIC) implementation. What I have so far is the following (with most of the operators and other code removed). template struct ControlBlock { …
Patrick Wright
  • 1,401
  • 7
  • 13
1
vote
2 answers

Need to Release a com_ptr_t before reassigning with CreateInstance?

In a C++ class with _com_ptr_t members, will memory leak if CreateInstance() is repeatedly used on the same pointer to get fresh instances of COM objects, without first performing a Release()? It's well documented that ref count is decremented when…
fitz
  • 43
  • 6
1
vote
1 answer

Move an object containing a unique_ptr to vector

Just wondering if there is a way to move an object holding a unique_ptr into a vector of those objects? Example: class A { public: std::unique_ptr ptr; }; std::vector objects; A myObject; //move myObject to objects??? Now, is…
1
vote
2 answers

Is there a way to make a smart pointer that points to either a std::ifstream or std::cin?

I want to take input from an istream from either a std::ifstream or std::cin depending on some condition. As far as I can get it working, I had to use a raw std::istream* pointer: int main(int argc, char const* argv[]) { std::istream…
bigyihsuan
  • 172
  • 1
  • 9