⚙️Go deeper — read the bookSmart pointers, from scratch— runnable code & full walkthrough →🧰Go deeper — read the bookImplement it yourself: the interview classics— runnable code & full walkthrough →

cpp core · high

How shared_ptr Ref-Counting Works

Watch strong/weak counts drive object lifetime: copies increment, scope-exit decrements, object dies at strong 0, control block at weak 0.

🔑 Key line

Strong count owns the object; weak count owns the control block. Object dies at strong 0; block dies at weak 0.

The code

auto sp1 = std::make_shared<Widget>(); // strong=1, weak=0
{
auto sp2 = sp1; // copy -> strong=2
auto sp3 = sp2; // copy -> strong=3
sp3->use();
} // sp2,sp3 destroyed -> strong=1
std::weak_ptr<Widget> wp = sp1; // weak=1 (strong stays 1)
sp1.reset(); // strong=0 -> ~Widget()
// wp.expired() == true; block freed when weak hits 0

What this lesson walks through

  1. 01make_shared: object + control block in one allocation
  2. 02Copy shares ownership -> strong = 2
  3. 03Another copy -> strong = 3
  4. 04Scope exit: destructors decrement -> strong = 1
  5. 05weak_ptr bumps the WEAK count, not strong
  6. 06strong -> 0: the object is destroyed
  7. 07Block survives while weak > 0
  8. 08weak -> 0: control block freed, nothing leaks

std::make_shared makes ONE heap allocation holding both the Widget and its control block. sp1 owns it: strong (use_count) = 1, weak = 0.

See it animated — step by step, at your own pace

Unlock the full interactive walkthrough of How shared_ptr Ref-Counting Works and 100+ animated C++ interview lessons.

← Previous
noexcept Moves & Vector Growth
Next →
shared_ptr Cycles & weak_ptr