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
3 answers

Why instantiating a shared_ptr calling destructor?

Can someone explain why is the destructor of class bar being called in the line where the object of the same type is being initialized? #include #include using namespace std; class bar { public: …
user1009285
  • 165
  • 1
  • 1
  • 11
1
vote
1 answer

RAII with std::function

Is std::function smart in nature like std::shared_ptr and std::unique_ptr? I guess no? I have a std::function which is a class member like below. class MyClass { typedef std::function Func; Func m_func; public: MyClass() { …
AdeleGoldberg
  • 1,289
  • 3
  • 12
  • 28
1
vote
1 answer

C++ - overload structure dereference operator and use it in unique_ptr

I have one implementation class and one wrapper class, and I want to access to implementation class instance through wrapper class with structure dereference (->) operator. So far, no problem. class Implementation { public: …
brakulla
  • 23
  • 4
1
vote
2 answers

Detect that std::shared_ptr is holding a raw array (and obtaining its size)

I'm working on (yet another) C++ serialization library that supports standard types such as containers. In particular I want to support smart pointers. C++17 introduced support for std::shared_ptr holding raw arrays (it knows to invoke delete [] in…
Emile Cormier
  • 28,391
  • 15
  • 94
  • 122
1
vote
2 answers

Dangling reference for smart pointer in C++

I understand that in C++ it is best/safer to use smart pointers in order to make sure we never miss freeing/deleting the allocated memory. Now I recently came across the following in a lecture about smart pointers in C++. This is the example: void…
JJ Adams
  • 481
  • 4
  • 17
1
vote
1 answer

copy parameter of a constructor into smart pointer

If a member of a class needs polymorphic behavior it needs to be either a pointer or a reference. If this member is initialized with a constructor parameter and should live as long as the class I see two options. Option 1: Copy reference parameter…
5634
  • 95
  • 6
1
vote
1 answer

Should you use smart pointers in C++ for low-level data structures, like for example, Linked Lists? A use case could be an interview setting

I have already implemented a templated Linked List which uses unique pointers internally. First I create a ListNode struct that holds this pointer to the next node and the data. Finally, it also has a handy function to turn it to string (for…
Avrdan
  • 343
  • 2
  • 13
1
vote
2 answers

Unique Pointer Initialization

I'm still new to c++, apologies if this is obvious, but I could not find a good answer after much googling. I wish I could write the following code. class Test { public: Test(); private: std::unique_ptr m_Dummy; }; Test::Test()…
nburn42
  • 697
  • 7
  • 25
1
vote
1 answer

How to limit the construction of an object to a couple of methods?

I have a Context class, and I would like everyone to manage it ONLY through unique_ptr(by the provided NewInstance static method). So I delete the copy/ctor for the class and provide a NewInstance method. class Context { public: Context(const…
Bin Yan
  • 117
  • 8
1
vote
1 answer

How to properly use memory pools C++11-style?

I'm trying to design the internal mechanics of a simple embedded application. Chunks of data arrive on the network which need to be delivered to components determined by an addressing mechanism. Multiple components may subscribe to the same address.…
1
vote
1 answer

Shared pointer in rust arrays

I have two arrays: struct Data { all_objects: Vec>; selected_objects: Vec>; } selected_objects is guarenteed to be a subset of all_objects. I want to be able to somehow be able to add or remove mutable…
mousetail
  • 7,009
  • 4
  • 25
  • 45
1
vote
1 answer

Is there a workaround to the limitation on pointer arithmetic with smart pointers in C++?

I'm working on a project and am not able to use bracket notation but must use smart pointers for arrays. However, as I've come to find, pointer arithmetic is not allowed with smart pointers. Is there a workaround for this? Edit: The project is for a…
1
vote
2 answers

Is it possible to make shared_ptr covariant?

I tried to make the following example. struct BaseSPtr{}; struct DerivedSPtr : public BaseSPtr{}; class Base{ public: //virtual shared_ptr function(); virtual BaseSPtr* function(); }; class Derived : public Base { …
Ionut Alexandru
  • 680
  • 5
  • 17
1
vote
1 answer

Error C2280 vector of objects that have unique_ptr members

I believe I know why this is happening, but being new to c++ I'm unsure what the correct way to handle it is (without using raw pointers). From my research what is happening is that when I attempt to push_back a Stage object into a vector a copy is…
whitwhoa
  • 2,389
  • 4
  • 30
  • 61
1
vote
2 answers

Modern way to have a map that can point-to or reference data of different types that has been allocated on the stack

Using raw pointers, this can be achieved like so: #include #include #include using namespace std; class base { public: virtual ~base(){} }; class derived1 : public base { public: virtual ~derived1(){} …
Blue7
  • 1,750
  • 4
  • 31
  • 55