⚙️Go deeper — read the bookSmart pointers, from scratch— runnable code & full walkthrough →

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 weak
std::weak_ptr<Node> prev; // observes, does not own

What this lesson walks through

  1. 01A and B own each other
  2. 02External owner goes away
  3. 03Cycle -> neither hits 0 -> LEAK
  4. 04Fix: make the back-link weak_ptr
  5. 05External owner goes away (fixed)
  6. 06A destroyed -> releases B -> B freed
  7. 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.

← Previous
How shared_ptr Ref-Counting Works
Next →
RAII & lock_guard