shared_ptr is a kind of Smart Pointer that is smart enough to automatically delete the associated pointer when its not used anywhere. Thus helps us to completely remove the problem of memory leaks and dangling Pointers. It follows the concept of Shared Ownership i.e. different shared_ptr objects can be associated with same pointer and internally uses the reference counting mechanism to achieve this. Each shared_ptr object internally points to two memory locations, 1.) Pointer to the object 2.) Pointer to control data that is used for reference counting How Shared Ownership works with the help of Reference Counting:

  • When a new shared_ptr object is associated with a pointer,then in its constructor it increases the refernce count associated with this pointer by 1.
  • When any shared_ptr object goes out of scope then in its destructor it decrements the reference count of the associated pointer by 1. If reference count becomes 0 then it means no other shared_ptr object is associated with this memory, in that case it deletes that memory using “delete” function.

When we bind a shared_ptr object with raw pointer like,

std::shared_ptr p1(new int());

In above line it allocates two memory on heap i.e. 1.) For int. 2.) A memory for Reference Counting that will be used to manange the count of shared_ptr objects attached with this memory. Initially it count will be 1. We can check that count with following function,


How not to assign pointer to shared_ptr,

std::shared_ptr p2 = new int(); // Will cause Compile Error

Because shared_ptr constructor taking an argument is Explicit and in above line we are calling it implicitly. Best way to create a new shared_ptr object is using std::make_shared,

std::shared_ptr p3 = std::make_shared(12);

std::make_shared makes one memory allocation for both the object and datastructure required for reference counting i.e. new operator will called only once. How to make shared_ptr object de-attach its attached pointer i.e. decrease its reference count by 1 and if reference count becomes 0 then it deleted the pointer 1.) Using reset() function: Reset the shared_ptr with no parameters,


in this case it will not point to any Pointer internally, hence its reference count will become 0. Reset the shared_ptr with new pointer,

p1.reset(new int(11));

in this case it will point to new Pointer internally, hence its reference count will again become 1. 2.) Using nullptr: set the shared_ptr object with nullptr. shared_ptr acts as normal pointer i.e. we can use * and -> with shared_ptr object and can also compare it like other shared_ptr objects; Complete example is as follows,