std::shared_ptr
std::shared_ptr lets several pointers co-own the same resource. The last one to die frees it.
Basic Usage
auto sp1 = std::make_shared<int>(42);auto sp2 = sp1; // both point to the same int
std::cout << sp1.use_count() << std::endl; // 2sp1.reset(); // sp1 no longer owns itstd::cout << sp2.use_count() << std::endl; // 1// int is freed when sp2 is destroyedHow It Works
shared_ptr keeps a reference count, a tally of how many shared_ptr instances point at the object. Hit zero and the object gets deleted.
Every shared_ptr holds two pointers: one to the object and one to a control block with the strong count (use_count()), the weak count and, when needed, a deleter. How that control block gets allocated depends on how you create the first owner:
The left side is the state after auto sp2 = sp1; above (each pointer also points straight at the int; those arrows are left out to keep it readable). With make_shared, the object is placed directly after its control block, so a single new covers both and the counts sit right next to the value they guard. With new, you pay for two heap allocations, and the control block has to remember where the separately allocated int lives so it can delete it.
shared_ptr is not free. Every owned object needs a control block on the heap (make_shared usually folds it into the same allocation as the object), and the refcount is updated atomically so copies on different threads stay safe. That atomicity covers the count only: two threads touching the pointed-to object still need their own synchronisation. Reach for unique_ptr if a single owner will do, and only escalate to shared_ptr when ownership genuinely is shared.
std::weak_ptr
weak_ptr observes a shared_ptr without affecting the reference count:
auto shared = std::make_shared<int>(42);std::weak_ptr<int> weak = shared;
if (auto locked = weak.lock()) { std::cout << *locked << std::endl; // 42} else { std::cout << "Object has been deleted" << std::endl;}weak_ptr breaks circular references:
struct Node { std::shared_ptr<Node> next; std::weak_ptr<Node> prev; // weak to break the cycle};Make prev a shared_ptr and two mutually-referencing nodes leak forever. Each keeps the other's count above zero.
Watch it happen. With both links as shared_ptr, neither node ever prints its goodbye.
When to Use Each
| Pointer | Use when... |
|---|---|
unique_ptr | Single owner, most common case |
shared_ptr | Multiple owners, graph structures |
weak_ptr | Non-owning observer, breaking cycles |
| Raw pointer | Non-owning, guaranteed-valid reference |
Common Pitfalls
Never wrap the same raw pointer in two shared_ptrs:
int *raw = new int(42);std::shared_ptr<int> sp1(raw);std::shared_ptr<int> sp2(raw); // BUG: double delete!Stick to make_shared, or copy an existing shared_ptr to share ownership.