Overview
- defined in the
std
namespace in the<memory>
header file.
They are crucial to the RAII or Resource Acquisition Is Initialization programming idiom.
unique_ptr
A unique_ptr
has exclusive ownership of the object it points to.
shared_ptr
Use reference counter, used when you want to assign one raw pointer to multiple owners. The raw pointer is not deleted until all shared_ptr
owners have gone out of scope or have otherwise given up ownership.
It use extra size: 2 pointers, one for object and one for the shared control block that contains the reference count.
weak_ptr
provides access to an object that is owned by one or more shared_ptr
instances, but does not participate in reference counting.
Use when you want to observe an object, but do not require it to remain alive. Required in some cases to break circular references between shared_ptr
instances.
Comparison
- Difference Between
unique_ptr
andshared_ptr
We can only have 1unique_ptr
but we can have multipleshared_ptr
. However,shared_ptr
may introduce some small overhead.