Strong vs Weak Counts in shared_ptr and How weak_ptr Breaks Cycles
Data Structure DesignModel answerLast updated
Describe the two reference counts in a shared_ptr control block, how weak_ptr uses them, why lock() is needed, and how a weak back-edge fixes a leaking ownership cycle.
Question
A C++ std::shared_ptr<T> does not track ownership inside the object itself. It uses a separate heap-allocated control block that stores two counters. Explain how that control block works and how std::weak_ptr<T> fits into it.
Your answer should cover:
- The two counters. What does the strong count measure, and what does the weak count measure?
- Two different lifetimes. What exactly happens when the strong count reaches zero, and what happens later when the weak count reaches zero?
- Why
lock()exists. Aweak_ptrcannot be dereferenced directly. Explain why a check followed by a use is unsafe in a multithreaded program, and howlock()avoids the problem. - Cycle breaking. Explain how a
weak_ptrstops a leak when two objects point at each other.
Scenario
Consider a list-like node type:
struct Node {
std::shared_ptr<Node> next; // owning link
std::weak_ptr<Node> prev; // non-owning link
};
Suppose node A refers to B through next, and B refers back to A. Describe what goes wrong if the link from B back to A is also a shared_ptr. Then walk through the order in which strong counts, weak counts, destructors and control blocks change when the back-link is a weak_ptr, and both local handles to A and B go out of scope.
State any caveats you consider important, such as what the thread-safety guarantee does and does not cover.
Hints
Hint 1
Destroying the managed object and freeing the control block are two separate events, and each is driven by a different counter.
Hint 2
Think about what a weak_ptr must still be able to read after the object is gone. That tells you why the control block has to outlive the object.
Hint 3
For lock(), consider an atomic 'increment only if the current value is not zero'. Why can this never resurrect a destroyed object?
Hint 4
In the cycle example, trace the strong count of each node after the local handles are dropped. Which count never reaches zero when both links are owning?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Short answer
A shared_ptr carries two pointers: one to the object and one to a control block. The control block holds a strong count (how many shared_ptrs own the object) and a weak count (how many weak_ptrs observe it, plus one shared by all strong owners in common implementations). It also holds the type-erased deleter and allocator.
The strong count decides when the object dies. The weak count decides when the control block is freed. A weak_ptr observes without owning, so it can outlive the object but not the block.
The two counters
| Event | What happens |
|---|---|
| Strong count reaches 0 | The deleter runs and ~T() executes. The strong owners then release their collective "+1" on the weak count. |
| Weak count reaches 0 | The control block is deallocated. |
The control block must outlive the object while any weak_ptr exists. Otherwise expired() and lock() would read freed memory to find out the object is gone. The weak count therefore keeps the block alive, and the strong owners hold one weak reference between them so the block cannot vanish while the object is still alive.
Why lock() exists
A weak_ptr deliberately cannot give you a raw T* or a dereference. Consider:
if (!w.expired()) {
use(*raw); // another thread may drop the last owner right here
}
This is a time-of-check to time-of-use race. The check says the object is alive, but another thread can release the last strong reference before you use it.
lock() fuses the check and the acquisition into one atomic step:
loop:
n = strong.load()
if n == 0: return empty shared_ptr
if CAS(strong, n, n + 1): return shared_ptr(obj, cb)
The count is incremented only if it is currently non-zero. Once you hold the returned shared_ptr, the strong count is at least 1, so the object cannot be destroyed while you use it. A dead object (count 0) can never be revived, because the CAS path never moves 0 to 1.
Usage:
if (auto sp = w.lock()) {
use(*sp); // safe: sp keeps the object alive
}
Memory ordering. Increments can be relaxed. The decrement needs release semantics, plus an acquire before running the destructor (or a single acq_rel), so all writes made by other owners are visible before ~T() runs.
Scope of the thread-safety guarantee:
- The control block is thread-safe: different
shared_ptrcopies can be copied and destroyed concurrently. - One
shared_ptrobject is not safe to modify from several threads at once. Usestd::atomic<std::shared_ptr<T>>(C++20) or external locking. - The pointee gets no synchronization. Access to
T's data needs its own protection.
Cycle breaking
If both links were shared_ptrs (A owns B, B owns A):
- When the local handles
aandbgo out of scope, each node's strong count drops from 2 to 1. - Each node is still owned by the other, so neither count reaches 0.
- No destructor runs. Both nodes and both control blocks leak, and nothing can reach them anymore.
Now make the back-edge non-owning. A owns B through next, and B observes A through prev:
auto a = std::make_shared<Node>();
auto b = std::make_shared<Node>();
a->next = b; // B: strong = 2
b->prev = a; // A: strong = 1, weak gains one observer
Teardown proceeds like this:
- Dropping
atakes A's strong count from 1 to 0, so~Aruns. A's strong side releases its collective weak "+1", but B'sprevstill holds a weak reference, so A's control block stays allocated. - Destroying A's members releases
A.next, so B's strong count goes from 2 to 1. - Dropping
btakes B's strong count to 0, so~Bruns. - Destroying
B.prevdecrements A's weak count to 0, so A's control block is freed. - B's weak count then reaches 0 and B's control block is freed.
Nothing leaks, and the order is deterministic. Between steps 1 and 3, b->prev.lock() returns an empty pointer, which is the correct way to detect that A is gone.
Design rule: ownership edges should form a DAG (parent owns child). Back-references such as child to parent, observer to subject, or cache to entry should be weak_ptr.
Complexity and cost
- Copying, destroying and creating a
weak_ptrare O(1), each a single atomic read-modify-write. lock()is a CAS loop. It is O(1) and retries only under contention.- Each
shared_ptris two pointers wide. The control block is roughly 16 to 32 bytes plus the deleter and allocator state. - Atomic operations on shared counters cost more than plain increments, and contention on a hot control block can become a bottleneck.
Common mistakes and edge cases
- Two owners built from one raw pointer. Creating two
shared_ptrs from the same raw pointer produces two control blocks and a double delete. Copy an existingshared_ptr, or inherit fromenable_shared_from_thiswhen an object must hand out owners of itself. shared_from_this()in a constructor. No owner exists yet, so it throwsbad_weak_ptr(C++17).make_sharedwith long-lived weak pointers. The object and control block share one allocation.~T()runs when the strong count hits 0, but the memory is returned only when the lastweak_ptrdies. A cache full of stale weak pointers can therefore hold on to large allocations.- Using
expired()as a guard. It is only a hint. Always acquire throughlock()and test the result. - Assuming shared_ptr makes the object thread-safe. It only protects lifetime bookkeeping.
- Very long owning chains. A long chain of
shared_ptrs destroys recursively and can overflow the stack. Tear down iteratively if lists can be large. - Overusing
shared_ptr. Preferunique_ptrwhen ownership is single. Reach forweak_ptronly for genuine non-owning observation.
Summary to say aloud
"The strong count controls the object's lifetime and the weak count controls the control block's lifetime. Destroying the object and freeing the block are separate events, so weak pointers can safely ask whether the object is still alive. lock() atomically increments the strong count only if it is non-zero, which removes the check-then-use race. In a parent and child cycle, making the back-edge a weak_ptr lets the strong counts reach zero in order, so both nodes are destroyed and both control blocks freed."