Differences between shared_ptr, unique_ptr and weak_ptr
🏹 Used to manage automatic memory allocation and deallocation.
Smart pointers in C++ (std::shared_ptr, std::unique_ptr and std::weak_ptr) are used to manage the automatic allocation and deallocation of memory, helping to avoid problems such as memory leaks and dangling pointers (pointers that point to a memory location that has already been deallocated).
Let’s see the difference between the main smart pointers!
std::shared_ptr
A shared pointer that can have multiple owners.
Keeps a reference counter. Each time a new copy of the shared_ptr is made, this counter is incremented. When all shared_ptrs that point to the same object are destroyed (counter reaches zero), the pointed object is deallocated.
Useful when you need multiple places in your code to share ownership of a resource.
Example:
Output:
std::unique_ptr
A unique pointer, which has exclusive ownership over the object. Only one unique_ptr can point to the same resource at a time.
Does not allow copies, only moves via std::move(move semantics) which ensures that the object will be managed by a single pointer.
Ideal when you want to ensure that a resource will not be shared.
Example:
Output:
std::weak_ptr
A weak pointer, which does not own the object. It observes an object managed by a shared_ptr without contributing to the reference count.
It is useful for avoiding reference cycles (when two or more shared_ptr reference each other, creating a cycle that prevents the memory from being freed).
Before accessing the object, you need to check if it is still valid using lock(), which returns a std::shared_ptr if the object still exists.
Example:
Output:
That is, shared_ptr: Owned by multiple owners, with reference counting to manage the destruction of the object. unique_ptr: Exclusive ownership, cannot be copied, only moved. weak_ptr: Observes the resource managed by a shared_ptr, but does not interfere with the reference counting, used to avoid reference cycles.