A reference-counted smart pointer for shared ownership: the object is freed when the last
shared_ptrto it goes away. Header:<memory>· Since: C++11
The pointer plus a heap-allocated control block holding a strong count
(owners) and a weak count (observers). Copying a shared_ptr bumps the strong
count; destroying one decrements it; at zero, the object is destroyed.
sp1 ┐
sp2 ┼──▶ [ control block: strong=3, weak=1 ] ──▶ the object
sp3 ┘
The count is atomic (thread-safe to copy/destroy from multiple threads), but
that makes copies more expensive than a unique_ptr move.
#include <memory>
void demo() {
auto p = std::make_shared<Widget>(42); // one allocation for object + control block
std::shared_ptr<Widget> q = p; // strong count → 2
p.use_count(); // 2 (approximate; for debugging)
p->use();
q.reset(); // count → 1; object still alive via p
}struct Node {};
std::vector<std::shared_ptr<Node>> graph;
auto n = std::make_shared<Node>();
graph.push_back(n); // both `n` and the vector co-own the node
// the Node lives until BOTH are gonestruct Field {};
struct Parent { Field field; };
// deleter stored in control block — and it runs even on a null pointer,
// so check fopen's result first: fclose(nullptr) is undefined
if (FILE* raw = std::fopen("x", "r")) {
std::shared_ptr<FILE> f{raw, &std::fclose};
}
// aliasing constructor: share ownership of `parent`, but point at a sub-object
auto parent = std::make_shared<Parent>();
std::shared_ptr<Field> fld{parent, &parent->field};- It's not free — don't default to it. Atomic refcount traffic, a control
block, and larger size than a raw/
unique_ptr. Useunique_ptrunless ownership is genuinely shared. Passingshared_ptrby value everywhere is a common performance smell — passconst T&/raw pointer when you don't take ownership. - Cycles leak. Two objects holding
shared_ptrto each other never reach count 0. Break the cycle withweak_ptrfor the back-edge. - Prefer
make_shared(single allocation, exception-safe) — but note it keeps the object storage alive as long as anyweak_ptrexists (object and control block share one block). With huge objects + long-lived weak_ptrs, the separate-allocationshared_ptr<T>(new T)can release object memory sooner. - The refcount is atomic; the pointed-to object is not. Concurrent reads are
fine; concurrent mutation of
*spstill needs your own synchronization. - Never make two independent control blocks for one object
(
shared_ptr<T> a{raw}; shared_ptr<T> b{raw};) → double free. Copy theshared_ptr, or useenable_shared_from_this.