Smart pointers
What unique_ptr, shared_ptr, weak_ptr and out_ptr each solve and how to choose between them, and why smart pointers hash by the stored pointer.
Key points
- Use
unique_ptrby default: exclusive ownership, the same size as a plain pointer with an empty deleter, and convertible toshared_ptrwhen needed. - Use
shared_ptronly when ownership really is shared by several parties and it cannot be determined who releases last; it needs an extra control block and does atomic count operations on copy and destruction. weak_ptrobserves an object managed byshared_ptrwithout extending its lifetime; it is used for caches, observer lists and breaking reference cycles.- The
hashand==of smart pointers are both computed from the stored pointerget(); to group by ownership, useowner_hashandowner_equal.
Components#
| Subclause | Components | Ownership |
|---|---|---|
| [unique.ptr] | unique_ptr, default_delete, make_unique |
Exclusive, transferable |
| [util.sharedptr] | shared_ptr, weak_ptr, bad_weak_ptr, owner_less/owner_hash/owner_equal, enable_shared_from_this |
Shared, reference-counted |
| [util.smartptr.hash] | hash<unique_ptr>, hash<shared_ptr> |
See below |
| [smartptr.adapt] | out_ptr, inout_ptr |
Working with C interfaces that output a pointer through a pointer parameter |
The details of shared_ptr are split across [util.smartptr.shared], [util.smartptr.weak], [util.smartptr.ownerless] and [util.smartptr.enab]. atomic<shared_ptr<T>> and atomic<weak_ptr<T>> are declared in <memory>, with their rules in [util.smartptr.atomic] in the atomic operations chapter.
How to choose#
- Use
unique_ptrby default. With an empty deleter it is the same size as a plain pointer, with no extra overhead; transferring ownership requires an explicitstd::move.shared_ptrhas a constructor takingunique_ptr&&, so you can switch to sharing at any time later; the reverse is not possible. - Use
shared_ptronly when ownership really is shared by several independent lifetimes and it cannot be determined who releases last. The cost is an extra control block (one more allocation, whichmake_sharedcan merge into one), atomic reference-count operations on every copy and destruction, and an object that is usually twice the size of a plain pointer. weak_ptris for observing without extending the lifetime: caches, observer lists, breaking reference cycles betweenshared_ptrs.- When you need an object on the heap but with value semantics, since C++26 consider [indirect] and [polymorphic]. Like
unique_ptrthey have exclusive ownership, but they can be copied (deep copy),constpropagates to the owned object, and comparisons compare values. They are not under [smartptr] but in [mem.composite.types]. - For non-owning observation use a plain pointer or reference. The standard has no
observer_ptr; it exists only in Library Fundamentals TS v2.
Smart pointers do not make the pointed-to object thread-safe, nor the smart pointer object itself. shared_ptr only guarantees that different shared_ptr objects operating concurrently on the same reference count do not cause a data race; concurrent reads and writes of the same shared_ptr object are still a data race ([util.sharedptr]).
Hashing [util.smartptr.hash]#
#include <cassert>
#include <memory>
#include <unordered_set>
struct P { int a, b; };
int main() {
auto sp = std::make_shared<P>();
std::shared_ptr<int> alias(sp, &sp->b); // shares ownership, different get()
std::unordered_set<std::shared_ptr<void>> s;
s.insert(sp);
s.insert(alias);
assert(s.size() == 2); // distinguished by get()
assert(std::hash<std::shared_ptr<P>>()(sp) ==
std::hash<P*>()(sp.get()));
}alias is created with the aliasing constructor ([util.smartptr.shared]); it shares the same control block as sp, but its stored pointer points to member b. The set treats them as two different elements.
¶1 Let UP be unique_ptr<T, D>. hash<UP> is enabled ([unord.hash]) if and only if hash<typename UP::pointer> is enabled. When enabled, hash<UP>()(p) has the same value as hash<typename UP::pointer>()(p.get()). These member functions are not guaranteed to be noexcept, because hashing a custom pointer type might throw.
¶2 For a shared_ptr<T> object p, hash<shared_ptr<T>>()(p) has the same value as hash<typename shared_ptr<T>::element_type*>()(p.get()).
Both are computed from the stored pointer get(), consistent with operator==, which also compares get(). So an aliasing shared_ptr and the original shared_ptr generally hash differently, even though they share ownership.
To group by ownership, for example to use weak_ptr as the key of an unordered container, use C++26's owner_hash and owner_equal ([util.smartptr.ownerless]). weak_ptr has no hash specialization: it has no get(), and its stored pointer could dangle at any moment.
In this clause
- 20.4.1Unique-ownership pointers[unique.ptr]done
- 20.4.1.1General[unique.ptr.general]
- 20.4.1.2Default deleters[unique.ptr.dltr]
- 20.4.1.3unique_ptr for single objects[unique.ptr.single]
- 20.4.1.4unique_ptr for array objects with a runtime length[unique.ptr.runtime]
- 20.4.1.5Creation[unique.ptr.create]
- 20.4.1.6Specialized algorithms[unique.ptr.special]
- 20.4.1.7I/O[unique.ptr.io]
- 20.4.2Shared-ownership pointers[util.sharedptr]done
- 20.4.2.1Class bad_weak_ptr[util.smartptr.weak.bad]
- 20.4.2.2Class template shared_ptr[util.smartptr.shared]done
- 20.4.2.2.1General[util.smartptr.shared.general]
- 20.4.2.2.2Constructors[util.smartptr.shared.const]
- 20.4.2.2.3Destructor[util.smartptr.shared.dest]
- 20.4.2.2.4Assignment[util.smartptr.shared.assign]
- 20.4.2.2.5Modifiers[util.smartptr.shared.mod]
- 20.4.2.2.6Observers[util.smartptr.shared.obs]
- 20.4.2.2.7Creation[util.smartptr.shared.create]
- 20.4.2.2.8Comparison[util.smartptr.shared.cmp]
- 20.4.2.2.9Specialized algorithms[util.smartptr.shared.spec]
- 20.4.2.2.10Casts[util.smartptr.shared.cast]
- 20.4.2.2.11get_deleter[util.smartptr.getdeleter]
- 20.4.2.2.12I/O[util.smartptr.shared.io]
- 20.4.2.3Class template weak_ptr[util.smartptr.weak]done
- 20.4.2.3.1General[util.smartptr.weak.general]
- 20.4.2.3.2Constructors[util.smartptr.weak.const]
- 20.4.2.3.3Destructor[util.smartptr.weak.dest]
- 20.4.2.3.4Assignment[util.smartptr.weak.assign]
- 20.4.2.3.5Modifiers[util.smartptr.weak.mod]
- 20.4.2.3.6Observers[util.smartptr.weak.obs]
- 20.4.2.3.7Specialized algorithms[util.smartptr.weak.spec]
- 20.4.2.4Class template owner_less[util.smartptr.ownerless]done
- 20.4.2.5Struct owner_hash[util.smartptr.owner.hash]
- 20.4.2.6Struct owner_equal[util.smartptr.owner.equal]
- 20.4.2.7Class template enable_shared_from_this[util.smartptr.enab]done
- 20.4.3Smart pointer hash support[util.smartptr.hash]
- 20.4.4Smart pointer adaptors[smartptr.adapt]done