Course Content
C++ Smart Pointers
C++ Smart Pointers
Introduction to Shared Pointers
Just like a unique pointer, a shared pointer is used to allocate and hold the address of a dynamically allocated object. The main differentiating factor between the two pointer types is that a shared pointer is shareable by design. It can safely have more than one owner. In fact, it should only be used when you need an object to have multiple owners.
How do Shared Pointers Work?
Unlike unique pointers, shared pointers maintain a reference count. The reference count of a shared pointer tracks the number of shared pointers that are currently referencing (owning) the same object.
When a shared pointer goes out of scope, or is explicitly reset, the reference count is automatically decremented. As soon as the reference count reaches 0, it means that no shared pointer is referencing the object any more, and the object's memory is automatically deallocated.
shared_pointer
#include <iostream> template <typename T> class SharedPointer { public: explicit SharedPointer(T* ptr = nullptr) : pointer(ptr), reference_count(new int(1)) {} SharedPointer(const SharedPointer& other) : pointer(other.pointer), reference_count(other.reference_count) { (*reference_count)++; } SharedPointer& operator=(const SharedPointer& other) { if (this != &other) { if (--(*reference_count) == 0) { delete pointer; delete reference_count; } pointer = other.pointer; reference_count = other.reference_count; (*reference_count)++; } return *this; } ~SharedPointer() { if (--(*reference_count) == 0) { delete pointer; delete reference_count; } } T* operator->() const { return pointer; } T& operator*() const { return *pointer; } private: T* pointer; int* reference_count; };
This is a foolproof way to ensure safe shared ownership of dynamic data. As, even when sharing data, the program is less susceptible to memory leaks/corruption, and you don't need to manually call delete
.
Thanks for your feedback!