Skip to content
LeetQuant
QD04 Modern C++ and Performance

QD04 · Modern C++ and Performance · Lesson 2 of 5

Smart Pointers and Ownership

unique_ptr for sole ownership, shared_ptr and the real cost of its control block and atomic reference count, weak_ptr for cycles, the make_ functions, and how function signatures communicate ownership.

17 min

Ownership is a design decision, not a pointer type

Every heap object needs exactly one answer to "who deletes this, and when?". Smart pointers encode that answer in the type, so the compiler enforces it:

  • std::unique_ptr<T>: exactly one owner. Move-only. Deletes the object when the owner is destroyed or reset.
  • std::shared_ptr<T>: several co-owners. The object dies when the last owner goes away.
  • std::weak_ptr<T>: an observer of a shared object that does not keep it alive and can check whether it still exists.
  • Raw pointer or reference: a non-owning borrow. The caller guarantees the object outlives the use.

The default is unique_ptr (or, better, no pointer at all: store the object by value). Reach for shared_ptr only when lifetime is genuinely shared and cannot be tied to one owner, such as an immutable market-data snapshot read by several threads that each finish at different times.

What they cost

#include <cstdio>
#include <cstdlib>
#include <memory>
#include <new>

static int g_allocs = 0;
void* operator new(std::size_t n) {
    ++g_allocs;
    if (void* p = std::malloc(n)) return p;
    throw std::bad_alloc{};
}
void operator delete(void* p) noexcept { std::free(p); }
void operator delete(void* p, std::size_t) noexcept { std::free(p); }

struct Quote { double bid = 0, ask = 0; };

int main() {
    std::printf("sizeof(Quote*)=%zu unique_ptr=%zu shared_ptr=%zu weak_ptr=%zu\n",
                sizeof(Quote*), sizeof(std::unique_ptr<Quote>),
                sizeof(std::shared_ptr<Quote>), sizeof(std::weak_ptr<Quote>));

    auto fileCloser = [](std::FILE* f) { if (f) std::fclose(f); };
    std::printf("unique_ptr<FILE, lambda>=%zu unique_ptr<FILE, void(*)(FILE*)>=%zu\n",
                sizeof(std::unique_ptr<std::FILE, decltype(fileCloser)>),
                sizeof(std::unique_ptr<std::FILE, void (*)(std::FILE*)>));

    g_allocs = 0;
    { std::shared_ptr<Quote> a(new Quote); }
    std::printf("shared_ptr(new Quote): %d allocations\n", g_allocs);
    g_allocs = 0;
    { auto b = std::make_shared<Quote>(); }
    std::printf("make_shared<Quote>():  %d allocation\n", g_allocs);
    g_allocs = 0;
    { auto u = std::make_unique<Quote>(); }
    std::printf("make_unique<Quote>():  %d allocation\n", g_allocs);

    auto p = std::make_shared<Quote>();
    auto q = p;                 // atomic increment
    std::weak_ptr<Quote> w = p; // weak count, not use count
    std::printf("use_count=%ld\n", p.use_count());
    p.reset(); q.reset();
    std::printf("expired=%d lock()==nullptr: %d\n", w.expired(), w.lock() == nullptr);
}

Output (64-bit Apple clang 17, libc++):

sizeof(Quote*)=8 unique_ptr=8 shared_ptr=16 weak_ptr=16
unique_ptr<FILE, lambda>=8 unique_ptr<FILE, void(*)(FILE*)>=16
shared_ptr(new Quote): 2 allocations
make_shared<Quote>():  1 allocation
make_unique<Quote>():  1 allocation
use_count=2
expired=1 lock()==nullptr: 1

Reading the numbers:

  • unique_ptr is free: the same size as a raw pointer, and its destructor is an inlined delete. A stateless deleter (a captureless lambda) adds nothing; a function-pointer deleter must be stored, doubling the size.
  • shared_ptr is two pointers: one to the object, one to a control block holding the strong count, the weak count and the deleter. shared_ptr<T>(new T) makes two allocations (object, then control block); make_shared makes one, placing the object inside the control block, which also improves locality.
  • Every copy of a shared_ptr increments the strong count and every destruction decrements it, using atomic read-modify-write instructions, because copies may live on different threads. The count is thread-safe; the pointed-to object is not.

Measuring the reference count

A micro-benchmark: call a non-inlined function 100 million times, passing a shared_ptr by value (one atomic increment and one decrement per call) versus passing const Quote&.

#include <chrono>
#include <cstdio>
#include <memory>

struct Quote { double bid = 100.0, ask = 100.5; };

__attribute__((noinline)) double by_value(std::shared_ptr<Quote> q) { return q->ask - q->bid; }
__attribute__((noinline)) double by_ref(const Quote& q) { return q.ask - q.bid; }

int main() {
    auto sp = std::make_shared<Quote>();
    constexpr int N = 100'000'000;
    using clk = std::chrono::steady_clock;
    for (int rep = 0; rep < 3; ++rep) {
        double s1 = 0, s2 = 0;
        auto t0 = clk::now();
        for (int i = 0; i < N; ++i) s1 += by_value(sp);
        auto t1 = clk::now();
        for (int i = 0; i < N; ++i) s2 += by_ref(*sp);
        auto t2 = clk::now();
        auto ns = [](auto d) { return std::chrono::duration<double, std::nano>(d).count(); };
        std::printf("shared_ptr by value: %.2f ns/call   const Quote&: %.2f ns/call   (%g %g)\n",
                    ns(t1 - t0) / N, ns(t2 - t1) / N, s1, s2);
    }
}

On the Apple M1 used to write this lesson:

shared_ptr by value: 14.92 ns/call   const Quote&: 1.16 ns/call   (5e+07 5e+07)
shared_ptr by value: 14.59 ns/call   const Quote&: 1.05 ns/call   (5e+07 5e+07)
shared_ptr by value: 15.13 ns/call   const Quote&: 1.15 ns/call   (5e+07 5e+07)

These timings are specific to this machine, compiler and a single uncontended thread; your numbers will differ. The ratio is the point: roughly 14 ns of extra work per call purely for reference counting, before any contention. When several cores copy the same shared_ptr, the control block's cache line bounces between them and the cost grows further. Hence the rule: pass shared_ptr by value only when the callee will keep a copy; otherwise pass const T& or T*.

weak_ptr and reference cycles

Reference counting cannot collect cycles. If A owns B and B owns A, both counts stay at 1 after every outside owner is gone, and neither destructor runs. Break the cycle by making one direction non-owning, with weak_ptr:

#include <cstdio>
#include <memory>

struct Node {
    const char* name;
    std::shared_ptr<Node> next;  // owning
    std::weak_ptr<Node> prev;    // non-owning back edge
    explicit Node(const char* n) : name(n) {}
    ~Node() { std::printf("~Node(%s)\n", name); }
};

struct LeakyNode {
    std::shared_ptr<LeakyNode> other;
    ~LeakyNode() { std::puts("~LeakyNode"); }  // never printed
};

int main() {
    {
        auto a = std::make_shared<LeakyNode>();
        auto b = std::make_shared<LeakyNode>();
        a->other = b;
        b->other = a;  // cycle: each keeps the other's count at >= 1
        std::printf("leaky: a.use_count=%ld\n", a.use_count());
    }
    std::puts("leaky scope ended");
    {
        auto a = std::make_shared<Node>("a");
        auto b = std::make_shared<Node>("b");
        a->next = b;
        b->prev = a;  // weak: does not bump a's use count
        std::printf("weak: a.use_count=%ld b.use_count=%ld\n", a.use_count(), b.use_count());
    }
    std::puts("weak scope ended");
}
leaky: a.use_count=2
leaky scope ended
weak: a.use_count=1 b.use_count=2
~Node(a)
~Node(b)
weak scope ended

No ~LeakyNode line ever appears: both objects leaked. To use a weak_ptr, call lock(), which atomically returns a shared_ptr (empty if the object has died). This also answers the classic "observer" question: a subscriber list of weak_ptr lets subscribers die without unregistering, and the publisher skips expired entries.

One subtlety of make_shared: because the object lives inside the control block, its memory is released only when the weak count also reaches zero. A long-lived weak_ptr to a large make_shared object keeps the whole block allocated (the destructor has run, but the bytes stay). If that matters, construct with shared_ptr<T>(new T) so the object's storage is freed separately.

Ownership in function signatures

The signature should tell the caller what happens to ownership without reading the body:

#include <cstdio>
#include <memory>
#include <vector>

struct Order { long id; int qty; };

void inspect(const Order& o) { std::printf("inspect %ld\n", o.id); }  // borrows, never null
void maybe_inspect(const Order* o) { std::printf("maybe %s\n", o ? "set" : "null"); }  // borrows, may be null

std::vector<std::unique_ptr<Order>> book;
void submit(std::unique_ptr<Order> o) { book.push_back(std::move(o)); }  // takes ownership

std::unique_ptr<Order> make_order(long id) { return std::make_unique<Order>(Order{id, 100}); }

int main() {
    auto p = make_order(7);
    inspect(*p);
    maybe_inspect(p.get());
    // submit(p);          // error: unique_ptr's copy constructor is deleted
    submit(std::move(p));  // ownership visibly transferred at the call site
    maybe_inspect(p.get());
    std::printf("book holds %zu order(s), first id %ld\n", book.size(), book[0]->id);
}
inspect 7
maybe set
maybe null
book holds 1 order(s), first id 7
SignatureMeaning
f(const T&) / f(T&)borrow; object must exist
f(const T*)borrow; may be null
f(std::unique_ptr<T>)sink: caller hands over ownership with std::move
f(std::unique_ptr<T>&)may reseat the caller's pointer (rare)
f(std::shared_ptr<T>)callee keeps a co-owner
f(const std::shared_ptr<T>&)callee might keep a copy; otherwise prefer T&
std::unique_ptr<T> make()factory: caller becomes the owner

A moved-from unique_ptr is guaranteed to be null, as the third output line shows. Prefer make_unique / make_shared over new: they name the type once, cannot leak if another argument's evaluation throws, and make_shared saves an allocation.

Worked example

design the ownership of an order gateway

A trading process has: an OrderBook holding live orders; a Strategy that reads the book and creates orders; a Gateway that sends orders and calls back into the strategy on fills; and a market-data thread that publishes an immutable Snapshot every few microseconds, read by three strategy threads that each take a different time to finish with it. Assign owners and pointer types, and identify the cycle risk.

Show solution
  1. Orders: the book is the single owner. Store them by value in a pre-allocated container (or as unique_ptr<Order> if their addresses must be stable and you are not pooling them). Everything else refers to an order by id or by raw pointer while the book guarantees it is alive.
  2. Strategy reads the book: a const OrderBook&. A borrow; the application owns both and destroys the strategy first.
  3. Snapshot: genuinely shared, read-only lifetime that ends when the slowest reader finishes, so std::shared_ptr<const Snapshot> built with make_shared. Each reader takes one copy per snapshot (one atomic increment), not one per field access: pass const Snapshot& down the call stack.
  4. Gateway and Strategy: if the strategy owns the gateway (unique_ptr<Gateway> or by value) and the gateway stores a shared_ptr<Strategy> for callbacks, that is a cycle and neither is ever destroyed. Make the callback non-owning: a raw Strategy* or reference if the strategy outlives the gateway by construction, or a weak_ptr<Strategy> checked with lock() if it may not.

Saying "shared_ptr only for the snapshot, and here is why" is a stronger interview answer than wrapping everything in shared_ptr to avoid thinking about lifetimes.

Knowledge check

Why does std::shared_ptr<T>(new T) perform two heap allocations while std::make_shared<T>() performs one?

Knowledge check

A hot function void price(std::shared_ptr<const Quote> q) only reads q and never stores it. What is the best change?

Knowledge check

Two objects hold std::shared_ptr to each other and nothing else refers to them. What happens?

Key takeaways

  • Default to values, then unique_ptr. unique_ptr costs nothing over a raw pointer.
  • shared_ptr is two words plus a control block, and every copy is an atomic increment; it measured roughly 14 ns extra per by-value call here, uncontended.
  • Use make_unique / make_shared; make_shared saves an allocation but ties the object's memory to the weak count.
  • Cycles of shared_ptr leak. Break them with weak_ptr or a raw back-pointer whose lifetime is guaranteed.
  • Signatures document ownership: borrow with T& / T*, sink with unique_ptr<T> by value, co-own with shared_ptr<T> by value.

Finished reading?

Answer the 3 knowledge checks to complete this lesson (0 done).