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=1std::weak_ptr<Widget> wp = sp1; // weak=1 (strong stays 1)sp1.reset(); // strong=0 -> ~Widget() // wp.expired() == true; block freed when weak hits 0What this lesson walks through
- 01make_shared: object + control block in one allocation
- 02Copy shares ownership -> strong = 2
- 03Another copy -> strong = 3
- 04Scope exit: destructors decrement -> strong = 1
- 05weak_ptr bumps the WEAK count, not strong
- 06strong -> 0: the object is destroyed
- 07Block survives while weak > 0
- 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.