Module 8 · Lesson 15 of 90

shared_ptr and the cost of shared ownership

Explain shared_ptr reference counting, reason about control-block and atomic-count costs, and use make_shared and the aliasing constructor correctly.

  • Beginner to advanced
  • 7 min read
  • 18 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM with g++ (GCC 13); no board needed

Your place in the module
By the end you can 4 objectives
  • Explain how shared_ptr counts owners and when the managed object is destroyed
  • Predict use_count() values across copies, moves and scope exits
  • Compare the allocation and run-time costs of make_shared versus a shared_ptr built from a raw pointer
  • Use the aliasing constructor to keep a parent object alive through a pointer to its member
Video coming soonshared_ptr and the cost of shared ownership
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Custom deleters and factory functions
  • unique_ptr<T, D> takes the deleter as a type parameter; a stateless deleter keeps it 8 bytes on 64-bit Linux, a function-pointer deleter makes it 16
  • shared_ptr type-erases its deleter into the control block, so the deleter is not part of the type and sizeof stays 16 bytes
  • make_unique and make_shared remove raw new and are exception-safe regardless of the language standard; make_shared also merges object and control block into one allocation
01

Counting owners with shared_ptr

3 min read

The previous lesson kept ownership exclusive with unique_ptr and custom deleters. This lesson asks what shared_ptr does when several parts of a program must own the same object, and what the atomic reference count and control block cost.

A concrete case from an embedded Linux gateway: a Config object holds the sampling interval and the server address, read from a file at startup. The sensor sampler, the logger and the uploader all need it, they run on different threads, and any of them may shut down first. With unique_ptr you would have to nominate one owner and prove it outlives all the others, which is exactly the lifetime bookkeeping RAII was meant to remove. std::shared_ptr<T>, from <memory>, solves this by making ownership shared: every copy of a shared_ptr is a full owner, and the object dies only when the last owner is gone.

The mechanism is . You can watch the count directly with use_count():

cpp
#include <memory>
#include <iostream>

struct Config { int interval_ms = 100; };

int main() {
    auto cfg = std::make_shared<Config>();
    std::cout << cfg.use_count() << '\n';     // 1
    {
        auto copy = cfg;                      // copy: a second owner
        std::cout << cfg.use_count() << '\n'; // 2
    }                                         // copy destroyed here
    std::cout << cfg.use_count() << '\n';     // 1
}
bash
g++ -Wall -Wextra -std=c++20 count.cpp -o count
./count
1
2
1

These three lines are fixed by the program's logic, not by the machine: any conforming implementation prints them. Copying a shared_ptr increments the count; destroying one decrements it; when the count reaches zero, the managed object is destroyed through its deleter (delete by default, or the custom deleter from the previous lesson if you supplied one). Moving a shared_ptr, using the move semantics you already know, transfers ownership without touching the count at all: the source becomes empty and the destination takes over the existing owner slot. That makes moves strictly cheaper than copies, a fact worth remembering when you pass ownership along a call chain.

Prefer std::make_shared<T>(args...) to build the object and its owner in one step. It constructs the T in place and returns a shared_ptr<T>; you never write new, and the next section shows why it is also the cheaper construction. use_count() itself is a debugging and teaching tool: in a program with threads, another thread can copy or release an owner between your read and your use of the value, so never write logic that depends on an exact count.

The life of an owner countmake_sharedcount = 1copycount = 2copydestroyedcount = 1last ownergonecount = 0objectdeleteddeleterrunsmake_sharedcount = 1copycount = 2copydestroyedcount = 1last ownergonecount = 0objectdeleteddeleterruns
The life of one owner count: copies raise it, destructions lower it, and zero deletes the object
02

The control block and what it costs

5 min read

A unique_ptr with the default deleter is just a raw pointer: one machine word, zero run-time overhead. A shared_ptr is two pointers: the stored pointer you access through get() and operator*, and a pointer to the . On 64-bit Ubuntu, whether x86-64 or the ARM64 of a Raspberry Pi, that is 16 bytes per shared_ptr, and every copy of the handle copies both pointers. The strong count counts owning shared_ptr instances; the weak count keeps the control block itself alive for weak_ptr, the non-owning observer the next lesson introduces.

The counts are atomic, and that is where the recurring cost lives. Incrementing or decrementing a count is an atomic read-modify-write: on x86-64 a lock-prefixed instruction, on ARM either an exclusive-access loop or a single atomic instruction depending on the core and compiler flags. Unlike a plain ++, it cannot be reordered or cached privately: the core must take exclusive ownership of the cache line holding the count. When several threads copy and release owners of the same object, that one cache line travels between cores on every copy and every destruction. On a four-core Raspberry Pi 4 this cache-line traffic is measurable in hot paths, and it is the price of the guarantee that two threads releasing the last two owners concurrently will destroy the object exactly once. The later lesson on atomic reference counting builds this mechanism by hand; here you only need the design rule: pass shared_ptr by const& when a function just uses the object, and copy it only when the function genuinely stores a new owner. The pointed-to object gets no protection at all from the count, so its fields still need the usual synchronization.

Step by stepWhat happens when a shared_ptr is destroyed
  1. Decrement the strong count atomically.

  2. If it reached zero: destroy the managed object by running its deleter (default: delete).

  3. Decrement the weak count atomically.

  4. If the weak count also reached zero: free the control block's memory. With no weak_ptr in play, steps 2 to 4 happen back to back.

Thread safety: the count, not the object, not the handle

Distinct shared_ptr instances that share a control block may be copied and destroyed on different threads safely: the atomic counts handle that. But two threads writing the same shared_ptr instance (one resetting it while another copies it) are a data race, and the managed object's fields are never protected by the count. You still need a mutex or atomics for the object's data, as the threading lessons cover.

Going deeperOne allocation or two: make_shared versus a raw pointer

std::make_shared<Config>() performs a single heap allocation (one call into the allocator, which on glibc 2.39 means malloc, see its man page): the control block and the Config object share one block, with the object embedded after the counts. std::shared_ptr<Config> p(new Config()) performs two: new Config allocates the object, then the shared_ptr constructor allocates a separate control block that stores the pointer and the deleter. Two allocations mean two allocator round trips, two headers, and two cache lines that may sit far apart, so dereferencing the object after touching the count can miss the cache twice.

The single allocation also removes a window between the two steps. With the raw-pointer form, new Config runs first and the shared_ptr constructor runs second. If the constructor's control block allocation throws std::bad_alloc, the standard requires the constructor to call delete on the pointer, so that step does not leak. The leak risk of the raw form is the one from the previous lesson, a function call such as f(std::shared_ptr<Config>(new Config), g()) compiled before C++17. make_shared has no such step: either the whole block exists and owns the object, or nothing happened.

There are two honest trade-offs. First, make_shared cannot take a custom deleter, because the object is destroyed in place inside the block; if you need fclose or a hardware-specific cleanup as the deleter, you construct from a pointer and pay for two allocations. Second, the object's memory is part of the control block, so it is only returned to the allocator when the weak count also reaches zero: a long-lived weak_ptr (next lesson) keeps the whole block, including a large object's bytes, reserved even after the object itself was destroyed. The separate-allocation form frees the object's memory as soon as the strong count hits zero. For a big buffer watched by long-lived observers, that difference matters on a memory-tight board.

One allocation or twomake_sharedshared_ptrfrom newHeap allocationsonetwoObject livesinsidecontrol blockseparateallocationObject memoryfreedat weak countzeroat strongcount zeroCustom deleternot possiblesupported
make_shared packs object and control block into one allocation; constructing from a raw pointer needs two
03

The aliasing constructor: one owner group, two pointers

2 min read

Suppose the uploader's API accepts std::shared_ptr<int> for a sequence number, but your sequence number is a field inside a Frame that the sensor pipeline owns. Handing out std::make_shared<int>(frame->seq) would copy the value and disconnect it from the frame. Handing out a raw &frame->seq would dangle the moment the pipeline drops the frame. The does exactly what you need: it joins the existing owner group while pointing somewhere inside the owned object.

cpp
#include <memory>
#include <iostream>

struct Frame { int seq; char payload[64]; };

int main() {
    auto frame = std::make_shared<Frame>();
    std::shared_ptr<int> seq(frame, &frame->seq);  // aliasing
    std::cout << frame.use_count() << '\n';        // 2
    frame.reset();                                 // drop the original owner
    *seq = 7;                                      // Frame is still alive
    std::cout << seq.use_count() << '\n';          // 1
}

The program prints 2 then 1, on any conforming implementation. Read the two lines carefully, because they contain the whole idea. After the aliasing construction there are two owners of one Frame, so use_count() is 2 for both handles: they share one control block. frame.reset() releases one owner, but the count does not reach zero, so the Frame is not destroyed and writing *seq = 7 is perfectly safe even though the only remaining handle has type shared_ptr<int>. The stored pointer and the owned object have come apart: seq.get() returns the address of the int member, while destruction, when the count finally reaches zero, runs the deleter for the whole Frame. The alias never deletes an int; it keeps a Frame alive and merely looks at one field of it.

This is why the control block stores the deleter separately from the stored pointer: the type shared_ptr<int> says nothing about what will actually be destroyed. The same decoupling is what lets shared_ptr carry a custom deleter without the deleter appearing in its type, unlike unique_ptr<T, D> from the previous lesson. Use aliasing whenever a consumer needs shared ownership of a piece of a larger object: a field of a configuration struct, an element of a shared buffer, a sub-object of a message. The rule to remember is: the alias owns what the original owned, and points where you told it to point.

Original handle vs aliasframeseq (alias)Stored pointerthe Frame&frame->seqControl blocksharedsame blockuse_count()same valuesame valueKeeps alivewhole Framewhole Frame
Two handles, one control block: the alias stores a member pointer but keeps the whole Frame alive

shared_ptr has one failure mode that counting cannot fix: if two objects own each other through shared_ptr members, each count is held above zero by the other, and neither object is ever destroyed. The next lesson, weak_ptr and breaking reference cycles, adds the non-owning observer that shares the control block without incrementing the strong count, which is how you cut that loop.

Key takeaways

  • A shared_ptr holds two pointers (stored pointer plus control block pointer), so it is 16 bytes on 64-bit Ubuntu, twice the size of a unique_ptr with no deleter
  • The strong and weak counts live in the control block and are updated with atomic read-modify-write operations, so every copy and destruction has a real run-time cost
  • make_shared allocates the object and the control block in one heap block, but that block is only freed once the weak count also reaches zero
  • The aliasing constructor shares another shared_ptr's control block while storing a different pointer; the owned object, not the pointed-to sub-object, is what gets destroyed
Reflect
  1. Explain to a colleague, in two sentences: explain how shared_ptr counts owners and when the managed object is destroyed
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Official documentation first. Links checked when the lesson was published.

Find your next step

↑ ↓ to move · Enter to open · Esc to close