Overview
- defined in the
stdnamespace 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.
unique_ptr<T> name(new T(args));
name.reset(); // Free the memory before we exit function block.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_ptrandshared_ptr
We can only have 1unique_ptrbut we can have multipleshared_ptr. However,shared_ptrmay introduce some small overhead.