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 a new shared pointer is constructed from the raw pointer, initialize the reference counter as 1.
- When a new shared pointer is assigned with some other shared pointer, the reference counter for that reference is increased by one.
- When an old shared pointer is assigned with some other shared pointer (both pointing to different memory location), the count of the reference pointed by the first shared pointer is decreased while the count of the second shared pointer is increased.
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.
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++.