Loading lessons...
Smart Pointers: shared_ptr and weak_ptr
Smart Pointers: shared_ptr and weak_ptr
Sometimes an object needs to be owned by many parties at once. std::shared_ptr handles that with a reference count.
shared_ptr shares ownership
std::shared_ptr<int> s1 = std::make_shared<int>(5);
The resource is a single heap int, and any number of shared_ptrs can point at it. Each copy bumps a reference count; when the last copy goes away, the count hits 0 and the memory frees.
Copies share the count
auto s2 = s1; // copying is allowed here
A shared_ptr perfectly allows copying. Copying adds one to the reference count; a copy that leaves first decrements it without destroying the object.
make_shared
auto p = std::make_shared<int>(10);
make_shared is the recommended way to create a shared_ptr. It allocates the object and the control block in one stroke, faster than a raw two-step shared_ptr(new).
weak_ptr breaks cycles
Two shared_ptrs that point at each other form a cycle - each keeps the other alive, so the memory is never freed. A weak_ptr observes an object without keeping it alive, so it can safely break cycles:
std::weak_ptr<int> w = s1; // observing only
auto locked = w.lock(); // attempts to get a shared_ptr
A weak_ptr keeps only a small side counter, so it doesn't keep the object alive. Convert it back to a temporary shared_ptr with lock(). If the object already died, lock() returns null.
TL;DR
shared_ptrowners share ownership through a reference count.- Copying a shared_ptr increments the counter; destruction decrements it.
std::make_sharedcreates the object with the control block; use it.weak_ptrobserves without keeping an object alive.- weak_ptr's main job breaks reference count cycles.