cpp core · high
shared_ptr Cycles & weak_ptr
Two shared_ptrs pointing at each other never reach refcount 0 (a leak); break the cycle with weak_ptr on the back-reference.
🔑 Key line
A shared_ptr cycle leaks because each object keeps the other alive; make the back-pointer a weak_ptr to break it.
The code
struct Node { std::shared_ptr<Node> next; // forward link std::shared_ptr<Node> prev; // back link -> CYCLE};auto a = std::make_shared<Node>();auto b = std::make_shared<Node>();a->next = b;b->prev = a; // a <-> b reference cycle
// Fix: make the back-link weakstd::weak_ptr<Node> prev; // observes, does not ownWhat this lesson walks through
- 01A and B own each other
- 02External owner goes away
- 03Cycle -> neither hits 0 -> LEAK
- 04Fix: make the back-link weak_ptr
- 05External owner goes away (fixed)
- 06A destroyed -> releases B -> B freed
- 07The rule
Node A holds a shared_ptr to B (next) and B holds one back to A (prev). An external sp also owns A, so A's strong count is 2 and B's is 1.
See it animated — step by step, at your own pace
Unlock the full interactive walkthrough of shared_ptr Cycles & weak_ptr and 100+ animated C++ interview lessons.