skip to content

In C++, what does a std::shared_ptr's control block hold, and what changes when you create the object with std::make_shared?

level: middleimportance: must knowfreq 70%

answer

  1. two pointers per shared_ptr
  2. strong count and weak count
  3. one allocation instead of two
  4. destroyed is not deallocated
  5. the last weak_ptr frees the block

basics

~20 s

In libc++ and libstdc++ the control block holds the strong count, the weak count and the deleter. std::make_shared builds the object inside that block, one allocation instead of two, but its storage is freed only after the last weak_ptr goes.

solid answer

~40 s

The standard specifies what `std::shared_ptr` does and leaves the layout to the library; libc++ and libstdc++ both allocate a **control block** that holds the strong count (how many `shared_ptr` own the object), the weak count (how many `weak_ptr` observe it) and the deleter, while each `shared_ptr` stores two pointers: the object and the block. `std::shared_ptr<Session>(new Session)` therefore makes two allocations. `std::make_shared<Session>()` builds the `Session` inside the control block, so one allocation does both — the standard says implementations should perform no more than one — with better locality. The catch: when the strong count reaches zero the destructor runs, but the storage belongs to the block, which lives until the weak count also reaches zero. A large object watched by long-lived `weak_ptr`s keeps its memory. `make_shared` also cannot take a custom deleter.

code

cpp · 29 lines
cpp
#include <cstdio>
#include <cstdlib>
#include <memory>
#include <new>

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

struct Session {
    char history[4096];                          // a large message backlog
    ~Session() { std::puts("  ~Session"); }
};

int main() {
    allocs = 0;
    std::shared_ptr<Session> a(new Session);     // object + separate control block
    std::printf("new: %d allocations\n", allocs);
    allocs = 0;
    auto b = std::make_shared<Session>();        // one block holds both
    std::printf("make_shared: %d allocation\n", allocs);
    std::weak_ptr<Session> watcher = b;
    std::puts("reset b:");
    b.reset();                                   // destructor runs, memory stays
    std::puts("reset watcher:");
    watcher.reset();                             // last weak_ptr gone: block freed
    std::puts("end:");
}

go deeper

for a junior

Know that shared_ptr counts its owners, deletes the object when the count reaches zero, and is usually created with make_shared.

for a middle

Explain the control block's two counts, why make_shared needs one allocation instead of two, and why shared_ptr is two pointers wide.

for a senior

Diagnose memory that outlives destroyed objects because make_shared blocks are pinned by stale weak_ptrs, and choose shared_ptr(new T) or allocate_shared where that matters.

for a principal

Treat the control block as a cost of every shared object - an allocation, two counters, two-pointer handles - when deciding whether shared ownership belongs in a design.

## What the standard specifies and what it leaves open `std::shared_ptr<T>` (header `<memory>`) shares ownership of one object among any number of `shared_ptr` instances, deletes it when the last of them is destroyed or reset, and lets `std::weak_ptr` observe it without owning. The standard describes this with observable behaviour — `use_count()`, `weak_ptr::expired()`, when the deleter runs — and never mandates a data structure. Every mainstream implementation uses the same one: a separately allocated **control block**, so it is the picture interviewers expect, as long as you name it as the libraries' design. ## Inside the control block In libc++ the base classes `__shared_count` and `__shared_weak_count` hold two `long` counters, `__shared_owners_` and `__shared_weak_owners_`, plus virtual functions that destroy the object and free the block. In libstdc++ `_Sp_counted_base` holds `_M_use_count` and `_M_weak_count`. Details differ — libc++ stores "owners minus one", libstdc++ keeps the weak count at "weak_ptrs plus one while any owner exists" — but the shape is the same: - **strong count**: the number of `shared_ptr` objects that own the object; at zero the object is destroyed; - **weak count**: the observers; at zero (with no owners) the control block itself is freed; - **the deleter and allocator**, type-erased, so `shared_ptr<T>`'s type does not depend on them (deleters have their own lesson); - for `make_shared`, **the object itself**. Each `shared_ptr` is two pointers wide in both libraries (16 bytes on a 64-bit target): the stored pointer that `get()` returns and the control-block pointer. They are separate because they can differ, for example after converting `shared_ptr<Derived>` to `shared_ptr<Base>`. ## Two ways to create one | creation | allocations | where the object lives | |---|---|---| | `std::shared_ptr<Session> p(new Session)` | two: the object, then the block | its own allocation | | `auto p = std::make_shared<Session>()` | one | inside the control block | The standard's remark on `make_shared` is that implementations **should perform no more than one memory allocation**, noting this gives efficiency equivalent to an intrusive smart pointer. The benefits: 1. one call to the allocator instead of two; 2. the counts and the object sit next to each other in memory, so touching both is cheaper; 3. no window where a raw owning pointer exists, as with any make function. ## The cost: destroyed is not deallocated Two lifetimes are tracked separately. When the **strong** count reaches zero, the object's destructor runs. When the **weak** count also reaches zero, the control block is freed. With `shared_ptr(new T)` the object's storage is freed at the first event. With `make_shared` the object's storage *is part of* the block, so it stays allocated until the last `weak_ptr` is gone. The counting-allocator example on this page shows exactly that on libc++: `~Session` prints when the last owner resets, and the storage is freed only when the `weak_ptr` is reset. That matters in a chat server where each `Session` carries a 4 KB message backlog and an observer list keeps `weak_ptr<Session>` entries that are swept only occasionally: every closed session's backlog memory stays allocated until its stale `weak_ptr` is erased. ## Diagnosing memory that does not drop The symptom in production looks like a leak that is not one: sessions close, their destructors run (logs or counters confirm it), yet resident memory stays high. A heap profile shows many live blocks of the size of `Session` plus a few dozen bytes — the `make_shared` control block with the object's storage inside it. The steps: 1. Confirm the destructors run, which rules out a `shared_ptr` cycle. 2. Find who holds `weak_ptr<Session>`: an observer list, a cache index, a lookup table swept rarely. 3. Either sweep expired entries promptly, or create the large objects with `std::shared_ptr<Session>(new Session)` so the storage is freed at destruction and only the small control block waits for the `weak_ptr`s. Moving the large buffer out of the object (a `std::vector` member, which frees its heap storage in the destructor) also works, because then only the small fixed part stays pinned. ## When to avoid make_shared - Large objects observed by `weak_ptr`s that routinely outlive the last owner. - A custom deleter is needed: `make_shared` has no parameter for one. - The constructor is private and only a class factory can call it; `make_shared` cannot reach it. - A custom allocator is needed: use `std::allocate_shared`, which keeps the single allocation. ## Common mistakes - Saying the count lives inside the managed object; that is an intrusive design, not `std::shared_ptr`. - Assuming `make_shared` frees memory as soon as the object dies. - Treating `use_count()` as including `weak_ptr`s; it counts only owners.

  • When would you avoid std::make_shared?
    When `weak_ptr`s routinely outlive the last owner of a large object, because `make_shared` ties the object's storage to the control block; when you need a custom deleter, which `make_shared` cannot take; and when the constructor is private and only a class factory can reach it. `std::allocate_shared` covers the custom-allocator case while keeping one allocation.
  • Why is a std::shared_ptr two pointers wide in common implementations?
    It stores the pointer that `get()` returns separately from the pointer to the control block, because the two can differ: a `shared_ptr<Base>` converted from `shared_ptr<Derived>`, an aliasing `shared_ptr` to a member, and the in-block object of `make_shared` all point somewhere other than the block's start. libc++ and libstdc++ are both 16 bytes on a 64-bit target; the standard does not fix the size.

  • make_shared frees the object's memory as soon as the last shared_ptr dies
  • The reference count is stored inside the managed object
  • make_shared and shared_ptr(new T) make the same number of allocations
  • A weak_ptr keeps the managed object alive
  • use_count() counts weak_ptrs as well as shared_ptrs