How a std::shared_ptr
works
std::shared_ptr
allows shared ownership of dynamically allocated objects. It keeps track of the number of shared references to an object through reference counting. When the reference count reaches zero, the object is automatically deallocated, preventing memory leaks. std::shared_ptr
is thread-safe, making it suitable for concurrent access. It can also be used for managing resources beyond memory and can be equipped with custom deleters.
It implements the *
and ->
dereferencing operators as well, so it can be used as a normal pointer. Moreover, it provides copy constructors and assignment operators.
The default constructor produces an empty (null) unique pointer, and you can check if a std::shared_ptr
is empty by testing if (ptr)
or using it in a boolean context.
We can swap, move, get, and release a std::shared_ptr
just as we do with std::unique_ptr
.