C/C++ Arena

Step 4 of 5

shared_ptr

std::shared_ptr<T> allows several owners. It keeps a reference count and deletes the object when the last owner goes away. use_count() shows how many owners there are.

auto a = std::make_shared<int>(7);   // count 1
auto b = a;                          // copying is fine: count 2

Prefer unique_ptr by default. Reach for shared_ptr only when ownership is genuinely shared.

Your turn: make the program print 1 2 3 2 by filling in the blanks.

Previous: Returning ownership Next: weak_ptr