How to Implement User Defined Shared Pointers in C++?

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++.

What is shared_ptr 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.

Reference Counting

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.

Points to Consider when Counting Number of References

When to Use Shared Pointer?

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.

C++ Program for User Defined Implementation of Shared Pointer

a reference counter class <span Class template representing a shared pointer operator pointer reference counter <span should have increased now to 2. pointer reference counter <span should have increased now to 3. out of scope. pointer reference counter <span should have decreased now to 2. out of scope. pointer reference counter <span should have decreased now to 1.
Output:
--- 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