shared_ptr is one of the smart pointer introduced as a wrapper to the old raw pointers in C++ to help in avoiding the risks and errors of raw pointers. In this article, we will learn how to implement our own user defined shared pointer in C++.
A std::shared_ptr is a container for raw pointers. It is a reference counting ownership model i.e. it maintains the reference count of its contained pointer in cooperation with all copies of the std::shared_ptr. So, the counter is incremented each time a new pointer points to the resource and decremented when destructor of the object is called.
It is a technique of storing the number of references, pointers or handles to a resource such as an object, block of memory, disk space or other resources.
An object referenced by the contained raw pointer will not be destroyed until reference count is greater than zero i.e. until all copies of std::shared_ptr have been deleted.
We should use shared_ptr when we want to assign one raw pointer to multiple owners. For more information and details about shared and other smart pointers, please read here.
--- Shared pointers ptr1 --- Address pointed : 0x1cbde70 Counter Value : 1 --- Shared pointers ptr1, ptr2 --- Address pointed : 0x1cbde70 Counter Value : 2 Address pointed : 0x1cbde70 Counter Value : 2 --- Shared pointers ptr1, ptr2, ptr3 --- Address pointed : 0x1cbde70 Counter Value : 3 Address pointed : 0x1cbde70 Counter Value : 3 Address pointed : 0x1cbde70 Counter Value : 3 --- Shared pointers ptr1, ptr2 --- Address pointed : 0x1cbde70 Counter Value : 2 Address pointed : 0x1cbde70 Counter Value : 2 --- Shared pointers ptr1 --- Address pointed : 0x1cbde70 Counter Value : 1