Skip to main content
Be Bitwise
C++Smart Pointers & Memory

std::shared_ptr

std::shared_ptr lets several pointers co-own the same resource. The last one to die frees it.

Basic Usage

cpp
auto sp1 = std::make_shared<int>(42);
auto sp2 = sp1; // both point to the same int
std::cout << sp1.use_count() << std::endl; // 2
sp1.reset(); // sp1 no longer owns it
std::cout << sp2.use_count() << std::endl; // 1
// int is freed when sp2 is destroyed

How 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.

Key Concept

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:

cpp
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:

cpp
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.

Try itChange prev to std::weak_ptr<Node> and run again: both destructors should fire.
C++ (GCC 9.2.0)

When to Use Each

PointerUse when...
unique_ptrSingle owner, most common case
shared_ptrMultiple owners, graph structures
weak_ptrNon-owning observer, breaking cycles
Raw pointerNon-owning, guaranteed-valid reference

Common Pitfalls

Never wrap the same raw pointer in two shared_ptrs:

cpp
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.