C++: ownership, moves and object lifetimes

When each C++ object dies and who decides: values and references, the stack and the heap, destructors and RAII, unique_ptr, shared_ptr and weak_ptr, moves, copy elision, noexcept and the rule of zero; every trace and timing from real runs on an Apple M1 Pro. Reading: 21 min, plus 13 in closed details. Data as of October 2026.
The idea in one sentenceEvery C++ object has exactly one lifetime, and it ends at a moment you can point to in the source: the closing brace of its scope, or the destruction of its owner; RAII ties resources to that moment, and moves hand an object's contents to a new owner instead of copying them, so ownership, not a garbage collector, decides when memory is freed.

The first figure is the whole page in two halves. Python: a, b and a dict entry are three names for one heap object; it dies when its reference count reaches 0, at a time no line of your code names, and a cycle waits for the cycle collector. C++: v is the object: 24 bytes on the stack holding a pointer to its heap buffer, which it owns. A reference r only observes. At the closing brace v's destructor frees the buffer. Every section below is a variation on this picture: who the owner is, when it dies, and how ownership moves.

You need: how a C++ program is compiled and what undefined behaviour means (C++: the essentials). Python is the bridge throughout; nothing else is assumed.

Lifetime: from the end of an object's constructor to the start of its destructor.
Owner: the object whose destructor ends another object's lifetime (a vector owns its buffer).
RAII: "resource acquisition is initialisation": a resource is held by an object whose destructor releases it.
Stack unwinding: destroying the locals of every scope an exception leaves.
unique_ptr, shared_ptr, weak_ptr: one owner; counted owners; an observer of counted owners.
lvalue, rvalue: an expression with a name that will be used again; a temporary about to disappear.
Move: building an object by taking another's contents (its heap buffer) instead of copying them.
Copy elision: the compiler builds a returned object directly in the caller's variable: no copy, no move.
Special members: destructor, copy and move constructors, copy and move assignment.

Python counts references; C++ gives each object one owner and frees it at a known line

In one screen: when does each object die?

Each row is a rule this page shows happening in a real run (Apple clang 17, -std=c++23 -O2, on an Apple M1 Pro; every trace below is the program's own output).

ObjectIts lifetime endsSeen in
A local variableat the closing brace of its block, in reverse order of construction; also during unwinding, when an exception leaves the block3: Scopes, Exception unwinding
A temporary (Tracer{"u"}, a function's return value)at the end of the full expression, the semicolon3: Temporaries
A temporary bound to a const T& or T&& localextended to that reference's lifetime3: Temporaries
A memberafter its class's destructor body, in reverse declaration order4: the cycle
A heap object owned by a unique_ptrwhen that one owner is destroyed or reset()4: unique_ptr
A heap object owned by shared_ptrswhen the last owning shared_ptr goes; never, if the owners form a cycle4: shared_ptr, the cycle
A global or staticafter main returns (a function-local static is built on first use)2
A moved-from objectat its usual time: a move transfers the contents, never the lifetime5: Copy vs move

1. Values, references and pointers

In Python every variable is a name bound to an object on the heap, and b = a binds a second name to the same object. In C++ a variable is the object: its bytes live where the variable lives. So assignment and initialisation copy, and a second name has to be asked for.

copy.cpp (lines 4 to 8)
int main() {
    std::vector<int> a{1, 2, 3};
    std::vector<int> b = a;    // a COPY: b gets its own three ints
    b.push_back(4);
    std::printf("a has %zu, b has %zu\n", a.size(), b.size());
Predict, then reveal: what sizes does each line print?
$ clang++ -std=c++23 -O2 -Wall -Wextra copy.cpp -o copy && ./copy
a has 3, b has 4
a has 4 after r.push_back
a has 5 after p->push_back; p == &a is 1
p is now null
copy.py
a = [1, 2, 3]
b = a          # no copy: a second name for the same list
b.append(4)
print(f"a has {len(a)}, b has {len(b)}")
$ python3.14 copy.py
a has 4, b has 4

The same three lines give "a has 4, b has 4" in Python (one list, two names) and "a has 3, b has 4" in C++ (two vectors). The two ways to ask for a second name:

Reference, T& r = a;Pointer, T* p = &a;
What it isanother name for an existing objecta variable holding an address (&a: "the address of a")
Using itexactly like using a*p is the object; p->f() is short for (*p).f()
Re-point itnever: bound once, when createdyes, p = &b;
Point at nothingnevernullptr
Keeps a alivenono

The last row is the one that matters on this page: neither reference nor pointer keeps a alive; they only refer to memory that a owns. A reference or pointer that outlives its object dangles, and reading through it is undefined behaviour, the root of every dangling-reference bug (the essentials page's undefined behaviour section and its UB gallery show them crash, or worse, not crash).

const marks something read-only, checked by the compiler. Its everyday use is the parameter type const T&: "let me read your object without copying it, and I promise not to change it". With pointers, const can apply to the pointed-at object or to the pointer itself; read the declaration right to left (int* const q: q is a const pointer to int).

Pass byT for small values (int, double, a pointer, a string_view); const T& to read a big object; T& to modify the caller's object; T* when "no object" is a valid answer.
What it costsCopies are real: passing a std::vector by value copies every element.
Common mistakesPassing big objects by value by accident; a reference or pointer that outlives its object.
const in three compile errors, and how to read a long C++ error
const.cpp
#include <string>

// const& : read without copying, and promise not to change it
int count_chars(const std::string& s) { return static_cast<int>(s.size()); }

int main() {
    const int limit = 10;
    limit = 11;                     // error: limit is const

    std::string name = "u0029";
    const std::string& view = name;
    view += "!";                    // error: view is a read-only name

    int x = 1, y = 2;
    const int* p = &x;              // pointer to const int: *p is read-only
    p = &y;                         // fine: p itself can move
    int* const q = &x;              // const pointer to int: q cannot move
    *q = 5;                         // fine: what it points at can change
    q = &y;                         // error
    return count_chars(name) + *p;
}
$ clang++ -std=c++23 -Wall -Wextra -c const.cpp -o /dev/null
const.cpp:8:11: error: cannot assign to variable 'limit' with const-qualified type 'const int'
    8 |     limit = 11;                     // error: limit is const
      |     ~~~~~ ^
const.cpp:7:15: note: variable 'limit' declared const here
    7 |     const int limit = 10;
      |     ~~~~~~~~~~^~~~~~~~~~
const.cpp:12:10: error: no viable overloaded '+='
   12 |     view += "!";                    // error: view is a read-only name
      |     ~~~~ ^  ~~~
<sdk>/usr/include/c++/v1/string:1363:69: note: candidate function not viable: 'this' argument has type 'const std::string' (aka 'const basic_string<char>'), but method is not marked const
 1363 |   _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 basic_string& operator+=(const basic_string& __str) {
      |                                                                     ^
<sdk>/usr/include/c++/v1/string:1372:3: note: candidate template ignored: requirement '__can_be_converted_to_string_view<char, std::char_traits<char>, char[2]>::value' was not satisfied [with _Tp = char[2]]
 1372 |   operator+=(const _Tp& __t) {
      |   ^
<sdk>/usr/include/c++/v1/string:1377:69: note: candidate function not viable: 'this' argument has type 'const std::string' (aka 'const basic_string<char>'), but method is not marked const
 1377 |   _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 basic_string& operator+=(const value_type* __s) {
      |                                                                     ^
show the remaining 14 lines
<sdk>/usr/include/c++/v1/string:1381:69: note: candidate function not viable: 'this' argument has type 'const std::string' (aka 'const basic_string<char>'), but method is not marked const
 1381 |   _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 basic_string& operator+=(value_type __c) {
      |                                                                     ^
<sdk>/usr/include/c++/v1/string:1387:69: note: candidate function not viable: 'this' argument has type 'const std::string' (aka 'const basic_string<char>'), but method is not marked const
 1387 |   _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 basic_string& operator+=(initializer_list<value_type> __il) {
      |                                                                     ^
const.cpp:19:7: error: cannot assign to variable 'q' with const-qualified type 'int *const'
   19 |     q = &y;                         // error
      |     ~ ^
const.cpp:17:16: note: variable 'q' declared const here
   17 |     int* const q = &x;              // const pointer to int: q cannot move
      |     ~~~~~~~~~~~^~~~~~
3 errors generated.
[exit code 1]

Three errors, all at compile time. The second shows a feature of C++ error messages you will meet constantly: the compiler lists every overload of += it tried and why each failed ("method is not marked const"). Read the first line and the line pointing at your own file; skim the candidates. The rest of copy.cpp (a reference and a pointer modifying a, then the pointer set to nullptr):

copy.cpp
#include <cstdio>
#include <vector>

int main() {
    std::vector<int> a{1, 2, 3};
    std::vector<int> b = a;    // a COPY: b gets its own three ints
    b.push_back(4);
    std::printf("a has %zu, b has %zu\n", a.size(), b.size());

    std::vector<int>& r = a;   // a REFERENCE: another name for a
    r.push_back(99);
    std::printf("a has %zu after r.push_back\n", a.size());

    std::vector<int>* p = &a;  // a POINTER: holds a's address
    p->push_back(7);           // -> follows the pointer
    std::printf("a has %zu after p->push_back; p == &a is %d\n", a.size(), p == &a);

    p = nullptr;               // a pointer can be re-pointed, or point at nothing
    std::printf("p is now %s\n", p ? "set" : "null");
}
$ clang++ -std=c++23 -O2 -Wall -Wextra copy.cpp -o copy && ./copy
a has 3, b has 4
a has 4 after r.push_back
a has 5 after p->push_back; p == &a is 1
p is now null

2. Where objects live: the stack, the heap and static storage

A C++ object lives in one of three kinds of storage, and the kind decides when it dies:

  • Automatic storage, "the stack": local variables. Each function call pushes a frame for its locals and pops it on return. Allocation is free (the stack pointer moves) and destruction happens at the closing brace }, in reverse order of creation.
  • Dynamic storage, "the heap": objects created with new (properly, with std::make_unique, section 4). They live until someone destroys them. Allocation calls the memory allocator (malloc), which costs tens of nanoseconds and can fragment memory; how it does that is Memory allocators' subject.
  • Static storage: globals and static variables, alive for the whole program.

Python puts every object on the heap and frees it when its reference count reaches zero (Memory allocators also owns reference counting and the cycle collector as memory behaviour). C++ lets you put most things on the stack. The stage draws one real run of stack_heap.cpp measured, the stack frame as a raised plate above the heap, then continues the same picture with a copy, a move and the closing brace:

  1. v on the stack, its elements on the heap. std::vector<int> v{1, 2, 3}; The std::vector object itself is 24 bytes on the stack (a pointer to the elements, the size, the capacity), at 0x16b03e640 in this run, and its elements live in a heap buffer it owns, at 0x105591420. The dots are the pointer that links them.
  2. The whole run, region by region. on_stack (0x16b03e65c) and also_on_stack (0x16b03e658, 4 bytes lower) sit beside v (24 bytes lower again): on this ARM Mac the stack grows towards lower addresses. on_heap, a unique_ptr, owns one int on the heap at 0x105591410, 16 bytes before v's elements; global_counter is in static storage at 0x104dc8000. The addresses change on every run: macOS randomises where each region starts.
  3. A copy duplicates the buffer. std::vector<int> b = v; gives b its own heap buffer, and the three ints are copied into it: two owners, two buffers. copy.cpp (section 1) prints "a has 3, b has 4" after b.push_back(4): the two are independent. From this step on, the lines are added for the picture and the positions are illustrative.
  4. A move hands the buffer over. std::vector<int> w = std::move(v); copies three pointers into w and nulls v's: the same buffer, no element touched, and v is left empty. moved_from.cpp (section 5) printed w.data() == old v.data(): 1, v.size() now 0.
  5. The closing brace frees, in reverse order. The destructors run from the last object constructed to the first: w frees the buffer it took, b frees its copy, the moved-from v has nothing to free, and on_heap frees its int. The frame is popped; global_counter lives until after main returns.
  6. A pointer that outlives its owner dangles. Had b.data() been saved in a global int* p, p would still hold the freed buffer's address after the brace. Reading through it is undefined behaviour; the essentials page's UB gallery shows such reads crash, or worse, not crash.

When the vector dies, its destructor frees the buffer. That pattern, a small owner on the stack and a big buffer on the heap, is how C++ gets automatic cleanup of heap memory, and it has a name: RAII. Why stack memory is fast (it is almost always in the CPU cache) and what an allocation costs on this machine are measured in C++: the machine underneath; the root page Topic: programming-languages draws the same records laid out in Python, C++ and Rust.

The program and its raw output
stack_heap.cpp
#include <cstdio>
#include <memory>
#include <vector>

int global_counter = 0;            // static storage: lives for the whole program

void show(const char* what, const void* p) { std::printf("%-28s %p\n", what, p); }

int main() {
    int on_stack = 1;                       // automatic storage (the stack)
    int also_on_stack = 2;
    auto on_heap = std::make_unique<int>(3); // dynamic storage (the heap)
    std::vector<int> v{1, 2, 3};            // the vector object is on the stack...

    show("&global_counter (static)", &global_counter);
    show("&on_stack", &on_stack);
    show("&also_on_stack", &also_on_stack);
    show("&v (the vector object)", &v);
    show("on_heap.get() (heap int)", on_heap.get());
    show("v.data() (its elements)", v.data());     // ...its elements are on the heap
    std::printf("sizeof(v) = %zu bytes, whatever v.size() is\n", sizeof(v));
}
$ clang++ -std=c++23 -O2 -Wall -Wextra stack_heap.cpp -o stack_heap && ./stack_heap
&global_counter (static)     0x104dc8000
&on_stack                    0x16b03e65c
&also_on_stack               0x16b03e658
&v (the vector object)       0x16b03e640
on_heap.get() (heap int)     0x105591410
v.data() (its elements)      0x105591420
sizeof(v) = 24 bytes, whatever v.size() is

3. Destructors and RAII

A class can define a constructor, which runs when an object is created, and a destructor, written ~ClassName(), which runs automatically when the object dies: at the closing brace for a local, when its owner dies for a member, when delete is called for a heap object. RAII means: tie every resource (memory, a file, a lock, a GPU buffer, a socket) to an object whose destructor releases it. Then you can never forget to release it, even when an exception jumps out of the function.

To watch it happen, this page uses a small class, Tracer, that prints a line from each special member function, numbers its objects #1, #2... and says whether each lives on the stack or the heap. The replay on the right steps through that real output, a few log lines per step: the code lines that caused the events (taken from std::source_location), the live objects, and the log. Lines starting with @ are the program's own STEP markers, with their line numbers.

Predict, then step: in Scopes, in what order are a, b and c destroyed? In Temporaries, which of t and u outlives its line?

  1. a, then b in an inner block. Both are constructed on the stack: a is #1 (line 15), b is #2 (line 17).
  2. The inner brace ends b. b dies at its inner brace, before c is even created.
  3. c is constructed as #3 at line 20, in the outer block, beside a.
  4. The function's brace: c, then a. At the end, c dies before a: reverse order of construction, always.

The lifetime extension works only for a reference bound directly to the temporary (or to one of its members); a reference returned by a function called on a temporary (make().items()), or a string_view of a temporary string, dangles at the semicolon. Unwinding is why RAII and exceptions work together, and why C++ code almost never needs finally.

Python bridge
with open(p) as f: is RAII you opt into for one block. In C++ every object behaves like a with block, and the "exit" is the destructor. Python's __del__ is not the equivalent: it runs whenever the reference count or the garbage collector gets to it.
Problem it solvesLeaks and forgotten cleanup, including on error paths.
What it costsNothing at run time beyond the destructor's own work.
Common mistakesHolding a resource in a raw pointer instead of an owning object; a destructor that throws (it must not: a second exception during unwinding terminates the program).
The Tracer class (tracer.h) and the whole traced program (lifetime.cpp)
tracer.h
// tracer.h: a class that reports every special member function call.
// Each object gets a number (#1, #2, ...) and says whether it lives on the stack or the heap.
#pragma once
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <source_location>
#include <string>
#include <utility>

inline const char* stack_anchor = nullptr;   // set to a local's address in main()
inline int next_id = 1;

inline const char* where(const void* p) {
    long d = static_cast<const char*>(p) - stack_anchor;
    return std::labs(d) < (8L << 20) ? "stack" : "heap";
}
#define STEP(text) std::printf("@%d %s\n", __LINE__, text)
// The line in lifetime.cpp that caused a constructor call (blank when called from inside the library)
inline int at(const std::source_location& l) {
    return std::strstr(l.file_name(), "lifetime.cpp") ? static_cast<int>(l.line()) : 0;
}
using Loc = std::source_location;

template <bool NoexceptMove>
struct BasicTracer {
    int id;
    std::string name;
    explicit BasicTracer(std::string n, Loc l = Loc::current()) : id(next_id++), name(std::move(n)) {
        std::printf("ctor #%d %s %s L%d\n", id, name.c_str(), where(this), at(l));
    }
    BasicTracer(const BasicTracer& o, Loc l = Loc::current()) : id(next_id++), name(o.name) {
        std::printf("copy #%d from #%d %s %s L%d\n", id, o.id, name.c_str(), where(this), at(l));
    }
    BasicTracer(BasicTracer&& o, Loc l = Loc::current()) noexcept(NoexceptMove) : id(next_id++), name(std::move(o.name)) {
        std::printf("move #%d from #%d %s %s L%d\n", id, o.id, name.c_str(), where(this), at(l));
    }
    BasicTracer& operator=(const BasicTracer& o) {
        name = o.name;
        std::printf("copy= #%d from #%d\n", id, o.id);
        return *this;
    }
    BasicTracer& operator=(BasicTracer&& o) noexcept(NoexceptMove) {
        name = std::move(o.name);
        std::printf("move= #%d from #%d\n", id, o.id);
        return *this;
    }
    ~BasicTracer() { std::printf("dtor #%d\n", id); }
};
using Tracer = BasicTracer<true>;     // move constructor marked noexcept
using TracerNX = BasicTracer<false>;  // the same class without noexcept
lifetime.cpp
#include "tracer.h"
#include <cstring>
#include <memory>
#include <stdexcept>
#include <vector>

// <helpers>
void by_value(Tracer) { STEP("inside by_value"); }
void by_ref(const Tracer&) { STEP("inside by_ref"); }
Tracer make(const char* n) { Tracer t{n}; return t; }
// </helpers>

// <scope>
void scope() {
    Tracer a{"a"};
    {
        Tracer b{"b"};
        STEP("end of inner block");
    }
    Tracer c{"c"};
    STEP("end of function");
}
// </scope>

// <copymove>
void copymove() {
    Tracer a{"a"};
    Tracer b = a;             // copy constructor
    Tracer c = std::move(a);  // move constructor: steals a's string
    std::printf("a.name is now \"%s\"\n", a.name.c_str());
    b = c;                    // copy assignment (b already exists)
    STEP("end of function");
}
// </copymove>

// <calls>
void calls() {
    Tracer a{"a"};
    by_ref(a);                // no new object
    by_value(a);              // a copy for the parameter
    by_value(std::move(a));   // a move for the parameter
    Tracer m = make("m");     // no copy, no move: built in place
    STEP("end of function");
}
// </calls>

// <growth>
template <class T>
void growth() {
    std::vector<T> v;
    v.push_back(T{"x"});
    STEP("capacity 1, now push y");
    v.push_back(T{"y"});
    STEP("capacity 2, now push z");
    v.push_back(T{"z"});
    STEP("end of function");
}
// </growth>

// <reserve>
void reserve() {
    std::vector<Tracer> v;
    v.reserve(3);             // one allocation up front
    v.emplace_back("x");      // built directly inside the vector
    v.emplace_back("y");
    v.emplace_back("z");
    STEP("end of function");
}
// </reserve>

// <unique>
void unique() {
    auto p = std::make_unique<Tracer>("h");   // the Tracer lives on the heap
    std::unique_ptr<Tracer> q = std::move(p);  // ownership moves; the Tracer does not
    std::printf("p is %s, q owns #%d\n", p ? "set" : "null", q->id);
    q.reset();                                 // the owner lets go: destroyed now
    STEP("end of function");
}
// </unique>

// <shared>
void shared() {
    auto s = std::make_shared<Tracer>("s");
    {
        std::shared_ptr<Tracer> t = s;         // a second owner
        std::printf("use_count %ld\n", s.use_count());
    }
    std::printf("use_count %ld\n", s.use_count());
    STEP("end of function");
}
// </shared>

// <unwind>
void unwind() {
    Tracer a{"a"};
    try {
        Tracer b{"b"};
        throw std::runtime_error("boom");
        STEP("never reached");
    } catch (const std::exception& e) {
        std::printf("caught %s\n", e.what());
    }
    STEP("end of function");
}
// </unwind>

// <cycle>
struct Node {
    Tracer t;
    std::shared_ptr<Node> next;   // owns the node it points at
    std::weak_ptr<Node> prev;     // observes only
    explicit Node(const char* n) : t{n} {}
};
void cycle() {
    {
        auto a = std::make_shared<Node>("a");
        auto b = std::make_shared<Node>("b");
        a->next = b;
        b->next = a;              // a cycle of owners
    }
    STEP("a and b are unreachable");
    {
        auto c = std::make_shared<Node>("c");
        auto d = std::make_shared<Node>("d");
        c->next = d;
        d->prev = c;              // the back edge only observes
    }
    STEP("end of function");
}
// </cycle>

// <temps>
void temps() {
    const Tracer& r = Tracer{"t"};                // bound to a const&: lives as long as r
    STEP("r is still alive");
    std::printf("size %zu\n", Tracer{"u"}.name.size());  // dies at the semicolon
    STEP("end of function");
}
// </temps>

int main(int argc, char** argv) {
    char here;
    stack_anchor = &here;
    const char* s = argc > 1 ? argv[1] : "";
    if (!std::strcmp(s, "scope")) scope();
    else if (!std::strcmp(s, "copymove")) copymove();
    else if (!std::strcmp(s, "calls")) calls();
    else if (!std::strcmp(s, "growth")) growth<Tracer>();
    else if (!std::strcmp(s, "growth_nx")) growth<TracerNX>();
    else if (!std::strcmp(s, "reserve")) reserve();
    else if (!std::strcmp(s, "unique")) unique();
    else if (!std::strcmp(s, "shared")) shared();
    else if (!std::strcmp(s, "unwind")) unwind();
    else if (!std::strcmp(s, "cycle")) cycle();
    else if (!std::strcmp(s, "temps")) temps();
    std::printf("@0 back in main\n");
}

Every scenario was compiled with clang++ -std=c++23 -O2 -Wall -Wextra lifetime.cpp (Apple clang 17) and run once; src/ca/run_all.sh records them all. The stack or heap label is a heuristic: an address within 8 MB of a local in main counts as stack.

4. Owning heap objects: unique_ptr, shared_ptr and weak_ptr

When an object must live on the heap (it must outlive the function, it is too big for the stack, or its exact type is decided at run time), do not write new and delete. Use a smart pointer: a small stack object that owns the heap object and deletes it in its destructor.

  • std::unique_ptr<T>: exactly one owner. It cannot be copied (two owners would delete twice), only moved (section 5): ownership is handed over and the source becomes null. It is the same size as a raw pointer and costs nothing extra. Create one with std::make_unique<T>(args...). This is the default.
  • std::shared_ptr<T>: shared ownership with a reference count, like a Python object. The object dies when the last shared_ptr to it dies. It costs a separate control block holding the counts, twice the size, and an atomic (thread-safe) increment or decrement on every copy.
  • std::weak_ptr<T>: observes an object owned by shared_ptrs without keeping it alive. It breaks reference cycles, which reference counting alone never frees: Python has a cycle collector; C++ does not.

Predict, then step: in the cycle, which Tracers are ever destroyed?

The stage replays three recorded scenarios of lifetime.cpp (each run numbers its Tracers from #1): owners on the stack plate, the objects and control blocks on the heap floor, the dots running along owning pointers.

  1. unique_ptr: one owner. auto p = std::make_unique<Tracer>("h"); The Tracer is created once (#1, on the heap). p is one pointer, 8 bytes, the size of an int*.
  2. Moving the owner, not the object. q = std::move(p): moving the unique_ptr moved only the 8-byte pointer, and p became null; the program prints p is null, q owns #1. The Tracer was never copied or moved.
  3. reset() frees it now. q.reset() destroyed it at that line, before the end of the function.
  4. shared_ptr: two owners, one count. s owns Tracer #1 and points at its control block; copying it into t adds a second owner: the count is 2 while t exists (the program prints use_count 2). Each shared_ptr is 16 bytes, two pointers.
  5. One owner leaves. t's block ends and the count is 1 after (use_count 1); the Tracer is untouched.
  6. The last owner leaves. At the end of the function the count reaches 0: the Tracer dies with the last owner, s.
  7. A cycle of owners leaks. a and b own each other, so when both locals go, each node still has a count of 1: no destructor ever runs for #1 and #2, and the memory leaks until the process exits.
  8. weak_ptr breaks the cycle. In the second block the back edge is a weak_ptr, so c's count reaches 0 and both nodes go. Note the order: #4 (d's Tracer) dies before #3 (c's), because destroying node c destroys its members in reverse declaration order: prev, then next (releasing d, whose count reaches 0), then t.

Copying a unique_ptr does not compile, and the error says why:

unique_copy.cpp
#include <memory>
#include <string>

int main() {
    auto p = std::make_unique<std::string>("weights.bin");
    auto q = p;              // error: a unique_ptr cannot be copied
    auto r = std::move(p);   // fine: ownership is transferred
}
$ clang++ -std=c++23 -Wall -Wextra -c unique_copy.cpp -o /dev/null
unique_copy.cpp:6:10: error: call to implicitly-deleted copy constructor of 'unique_ptr<string>'
    6 |     auto q = p;              // error: a unique_ptr cannot be copied
      |          ^   ~
<sdk>/usr/include/c++/v1/__memory/unique_ptr.h:221:55: note: copy constructor is implicitly deleted because 'unique_ptr<std::string>' has a user-declared move constructor
  221 |   _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX23 unique_ptr(unique_ptr&& __u) _NOEXCEPT
      |                                                       ^
1 error generated.
[exit code 1]

What an owner costs per call

ptr_cost.cpp measured on the M1 Pro (Apple clang 17, -O2, best of 5 runs, load average 6.70): one non-inlined call that reads an int, 100 million times. Passing a raw pointer, a const unique_ptr& or a const shared_ptr& costs the same, 0.96 ns per call. Passing the shared_ptr by value copies it, two atomic count updates: 13.50 ns. With 4 threads copying the same shared_ptr, every update fights for the cache line holding the count: 302.42 ns per call per thread (why a shared line is that slow is measured in C++: the machine underneath).

So pass a smart pointer only when the callee takes part in ownership (the C++ Core Guidelines' rule R.30); a function that only uses the object takes T&, const T& or T*. Sizes on this Mac (sizeof, in bytes): int* 8, std::unique_ptr<int> 8, std::shared_ptr<int> 16 (a pointer to the object and one to the control block).

Owning costs nothing until you copy a shared_ptr, and much more when threads share one

Logarithmic scale; best of 5 runs on the M1 Pro, nanoseconds per call.

Ruleunique_ptr by default; shared_ptr only when ownership is genuinely shared (a cache entry used by several requests); raw pointers and references only to observe an object someone else owns.
What it costsunique_ptr: nothing. shared_ptr: 16 bytes, a control block allocation, atomic count updates.
Common mistakesshared_ptr everywhere "to be safe" (slow and hides who owns what); two shared_ptrs made separately from one raw pointer (two counts, double delete); cycles of shared_ptr.
Rust bridge
Box<T> is unique_ptr; Rc<T> and Arc<T> are shared_ptr without and with atomic counts; Weak is weak_ptr. Rust's compiler enforces the "do not use after move" rule that C++ only recommends: Rust: lifetimes, smart pointers, threads and unsafe.
The benchmark (ptr_cost.cpp), its output, and every sizeof on this Mac
ptr_cost.cpp
// What an owner costs per call: the same function called 100 million times with the object passed
// as a raw pointer, a const unique_ptr&, a const shared_ptr&, and a shared_ptr by value (a copy: two atomic
// count updates). Then 4 threads copying one shared_ptr at once, all updating the same count.
// noinline plus an empty asm statement with a memory clobber keep every call real (without them clang hoisted
// the read-only calls out of the loop and printed 0.00 ns); best of 5 runs; ns per call.
#include <atomic>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <memory>
#include <thread>
#include <vector>

#define NOINLINE __attribute__((noinline))
#define KEEP asm volatile("" ::: "memory")
NOINLINE long by_raw(const int* p) { KEEP; return *p; }
NOINLINE long by_uref(const std::unique_ptr<int>& p) { KEEP; return *p; }
NOINLINE long by_sref(const std::shared_ptr<int>& p) { KEEP; return *p; }
NOINLINE long by_sval(std::shared_ptr<int> p) { KEEP; return *p; }

constexpr long N = 100'000'000;
volatile long sink;

template <class F> double best_ns(F f) {
    double best = 1e30;
    for (int r = 0; r < 5; ++r) {
        auto t0 = std::chrono::steady_clock::now();
        long s = 0;
        for (long i = 0; i < N; ++i) s += f();
        sink = s;
        double ns = std::chrono::duration<double, std::nano>(std::chrono::steady_clock::now() - t0).count() / N;
        if (ns < best) best = ns;
    }
    return best;
}

int main() {
    double load[1];
    getloadavg(load, 1);
    std::printf("load average %.2f\n", load[0]);
    auto u = std::make_unique<int>(1);
    auto s = std::make_shared<int>(1);
    std::printf("raw pointer              %.2f ns per call\n", best_ns([&] { return by_raw(u.get()); }));
    std::printf("const unique_ptr&        %.2f ns per call\n", best_ns([&] { return by_uref(u); }));
    std::printf("const shared_ptr&        %.2f ns per call\n", best_ns([&] { return by_sref(s); }));
    std::printf("shared_ptr by value      %.2f ns per call\n", best_ns([&] { return by_sval(s); }));
    // 4 threads, each passing the same shared_ptr by value: the count's cache line moves between cores
    for (int threads : {1, 4}) {
        double best = 1e30;
        for (int r = 0; r < 5; ++r) {
            std::vector<std::thread> ts;
            std::atomic<int> ready{0};
            auto t0 = std::chrono::steady_clock::now();
            for (int t = 0; t < threads; ++t)
                ts.emplace_back([&] {
                    ready++;
                    while (ready < threads) {}
                    long acc = 0;
                    for (long i = 0; i < N / 10; ++i) acc += by_sval(s);
                    sink = acc;
                });
            for (auto& t : ts) t.join();
            double ns = std::chrono::duration<double, std::nano>(std::chrono::steady_clock::now() - t0).count() / (N / 10);
            if (ns < best) best = ns;
        }
        std::printf("by value, %d thread%s on one shared_ptr: %.2f ns per call per thread\n", threads, threads > 1 ? "s" : " ", best);
    }
}
$ clang++ -std=c++23 -O2 -Wall -Wextra ptr_cost.cpp -o ptr_cost && ./ptr_cost
load average 6.70
raw pointer              0.96 ns per call
const unique_ptr&        0.96 ns per call
const shared_ptr&        0.96 ns per call
shared_ptr by value      13.50 ns per call
by value, 1 thread  on one shared_ptr: 13.46 ns per call per thread
by value, 4 threads on one shared_ptr: 302.42 ns per call per thread

The single-thread "by value" lines appear twice (13.50 and 13.46 ns) because the 1-thread run repeats the measurement through the threaded harness, including thread start-up. The empty asm statement matters: without it clang saw that the read-only calls return the same value every time, hoisted them out of the loop and printed 0.00 ns.

sizes.cpp
#include <cstdio>
#include <functional>
#include <memory>
#include <optional>
#include <span>
#include <string>
#include <string_view>
#include <vector>

struct Plain   { double x; void f() {} };
struct Virtual { double x; virtual void f() {} virtual ~Virtual() = default; };

int main() {
    std::printf("%-30s %zu\n", "int*", sizeof(int*));
    std::printf("%-30s %zu\n", "std::unique_ptr<int>", sizeof(std::unique_ptr<int>));
    std::printf("%-30s %zu\n", "std::shared_ptr<int>", sizeof(std::shared_ptr<int>));
    std::printf("%-30s %zu\n", "std::vector<int>", sizeof(std::vector<int>));
    std::printf("%-30s %zu\n", "std::string", sizeof(std::string));
    std::printf("%-30s %zu\n", "std::string_view", sizeof(std::string_view));
    std::printf("%-30s %zu\n", "std::span<int>", sizeof(std::span<int>));
    std::printf("%-30s %zu\n", "std::optional<int>", sizeof(std::optional<int>));
    std::printf("%-30s %zu\n", "std::function<int(int)>", sizeof(std::function<int(int)>));
    std::printf("%-30s %zu\n", "Plain {double; f()}", sizeof(Plain));
    std::printf("%-30s %zu\n", "Virtual {double; virtual f()}", sizeof(Virtual));
}
$ clang++ -std=c++23 -O2 -Wall -Wextra sizes.cpp -o sizes && ./sizes
int*                           8
std::unique_ptr<int>           8
std::shared_ptr<int>           16
std::vector<int>               24
std::string                    24
std::string_view               16
std::span<int>                 16
std::optional<int>             8
std::function<int(int)>        32
Plain {double; f()}            8
Virtual {double; virtual f()}  16

5. Moves

Copy-by-default has an obvious cost: returning a vector of a million elements, or putting a string into a container, would copy every byte. C++11 added moves: when the source object is about to die anyway, the new object may steal its heap buffer (copy three pointers, set the source's to null) instead of copying the contents. The compiler needs to know when stealing is safe, so it sorts expressions into two families (simplified):

  • an lvalue has a name and an address you can take: a, v[3], *p. It will be used again, so it must be copied.
  • an rvalue is a temporary about to disappear: make_name(), a + b, Tracer{"x"}. It may be moved from.

A class gets a move constructor T(T&& other) (the && means "rvalue reference": it binds only to things that may be moved from) alongside its copy constructor T(const T& other), and overload resolution picks one. std::move(x) moves nothing. It is a cast that says "treat x as an rvalue; I will not need its value again" (cppreference: "exactly equivalent to a static_cast to an rvalue reference type"); the move constructor that it selects does the stealing.

Predict, then step: in Copy vs move, which constructors run, and what is left in a.name? In Passing and returning, how many Tracers are made in total, and where does m come from?

  1. a is constructed as #1 on the stack (line 27).
  2. Copy. Tracer b = a; runs the copy constructor: #2 gets its own copy of the name.
  3. Move. Tracer c = std::move(a); runs the move constructor: #3 takes #1's string. The moved-from a is still a valid object, but its value is unspecified; libc++ leaves the string empty (the program prints a.name is now "").
  4. Assignment, not construction. b = c is an assignment (b already exists), so no object is created: #2 takes a copy of #3's name.
  5. Reverse order at the brace. #3, #2, then #1: the moved-from a's destructor runs at the end like any other.

The standard only promises "valid but unspecified" for a moved-from object: you may assign to it or destroy it; do not read it.

That last line is copy elision: since C++17, returning a temporary constructs the result directly in the caller's variable, guaranteed, and compilers do the same for a returned local variable in practice (cppreference). So return big objects by value, and never write return std::move(local);, which can only prevent elision. What moving buys, and one trap:

moved_from.cpp (lines 7 to 20)
    std::string s = "a string long enough to live on the heap";
    std::string t = std::move(s);       // t steals s's heap buffer
    std::printf("t: %zu chars, s: %zu chars\n", t.size(), s.size());
    s = "reusable";                     // a moved-from object can be assigned to
    std::printf("s: %s\n", s.c_str());

    std::vector<int> v(1'000'000, 7);
    const int* before = v.data();
    std::vector<int> w = std::move(v);  // O(1): three pointers change hands
    std::printf("w.data() == old v.data(): %d, v.size() now %zu\n", w.data() == before, v.size());

    const std::string c = "const";
    std::string d = std::move(c);       // compiles, but COPIES: you cannot steal from const
    std::printf("c after 'move': %s\n", c.c_str());
$ clang++ -std=c++23 -O2 -Wall -Wextra moved_from.cpp -o moved_from && ./moved_from
t: 40 chars, s: 0 chars
s: reusable
w.data() == old v.data(): 1, v.size() now 0
c after 'move': const

The million-element vector changed hands in constant time: w owns the very same buffer, and v is empty. A moved-from string can be assigned to and reused. The last line is the trap: std::move of a const object silently copies, because a move constructor needs to modify its source. It compiles and copies, with no warning.

6. Why noexcept on a move constructor matters: one vector, two classes

A std::vector keeps its elements in one buffer. When the buffer is full, push_back allocates a bigger one, transfers the old elements and frees the old buffer. It would like to move them, but if a move threw an exception halfway, the old buffer would be half-emptied and the vector could not restore it. So the standard library moves only if the move constructor is declared noexcept ("this never throws"); otherwise it copies, to keep its strong exception guarantee (std::move_if_noexcept). The replay runs the same three push_back calls on two versions of Tracer that differ only in that one keyword.

Predict, then step: without noexcept, how many of the transfers become copies?

  1. push_back(x) into an empty vector. The temporary T{"x"} (#1) is built on the stack, moved into the new heap buffer by the library (#2), and destroyed at the semicolon.
  2. y: the buffer is full, so the vector reallocates. The new element is moved into the bigger buffer first (#4 from y's temporary #3), then x is moved across (#5 from #2); the old buffer's x and the temporary are destroyed.
  3. z: it reallocates again. z goes in (#7), then x and y are moved across (#8, #9); the old elements #5 and #4 and the temporary #6 are destroyed. No copies at all.
  4. The vector dies and destroys its three elements: #7, #9, #8.

Both versions make 9 objects. With noexcept, each reallocation moves the old elements (cheap); without it, the same code copies them: 3 copies here (x at the second growth, x and y at the third). For a vector of strings each copy is a heap allocation and a byte copy, on every growth. With reserve(3) and emplace_back, three objects are built directly in the vector's buffer: no temporaries, no moves. The compiler writes a noexcept move constructor for you when every member's is noexcept (the rule of zero, below), which is one more reason not to write them by hand.

Details in the growth traces

The capacities on this libc++ go 1, 2, 4: the third push_back reallocates again. Each new element is constructed in the new buffer before the old elements are transferred (#7 before #8 and #9), so the argument stays valid even if it referred to an element of the old buffer. At the end, libc++ destroys the elements last to first (#7, #9, #8 are z, y, x); the standard does not fix that order for a vector.

$ clang++ -std=c++23 -O2 -Wall -Wextra lifetime.cpp -o lifetime && ./lifetime growth_nx
ctor #1 x stack L51
move #2 from #1 x heap L0
dtor #1
@52 capacity 1, now push y
ctor #3 y stack L53
move #4 from #3 y heap L0
copy #5 from #2 x heap L0
dtor #2
dtor #3
@54 capacity 2, now push z
ctor #6 z stack L55
move #7 from #6 z heap L0
copy #8 from #5 x heap L0
copy #9 from #4 y heap L0
dtor #5
dtor #4
dtor #6
@56 end of function
dtor #7
dtor #9
dtor #8
@0 back in main

7. The rule of zero and the rule of five

Five special member functions control a class's lifetime: destructor, copy constructor, copy assignment, move constructor, move assignment. The compiler writes all five for you, member by member. That is correct when every member manages itself (std::vector, std::string, std::unique_ptr): the rule of zero says write none of them. A class that owns a raw resource must write all five (the rule of five), because the compiler-written copy would copy the pointer, not the buffer:

rule_of_five.cpp (lines 5 to 29)
// A class that owns a raw buffer must write all five special members.
class Buffer {
    float* data_;
    std::size_t n_;
public:
    explicit Buffer(std::size_t n) : data_(new float[n]()), n_(n) {}
    ~Buffer() { delete[] data_; }                                   // 1 destructor
    Buffer(const Buffer& o) : data_(new float[o.n_]), n_(o.n_) {    // 2 copy constructor
        std::memcpy(data_, o.data_, n_ * sizeof(float));
    }
    Buffer& operator=(const Buffer& o) {                            // 3 copy assignment
        Buffer tmp(o);
        swap(tmp);
        return *this;
    }
    Buffer(Buffer&& o) noexcept                                     // 4 move constructor
        : data_(std::exchange(o.data_, nullptr)), n_(std::exchange(o.n_, 0)) {}
    Buffer& operator=(Buffer&& o) noexcept {                        // 5 move assignment
        Buffer tmp(std::move(o));
        swap(tmp);
        return *this;
    }
    void swap(Buffer& o) noexcept { std::swap(data_, o.data_); std::swap(n_, o.n_); }
    std::size_t size() const { return n_; }
};
rule_of_five.cpp (lines 31 to 35)
// Rule of zero: let a member that already manages itself do the work.
#include <vector>
struct Buffer0 {
    std::vector<float> data;   // the compiler writes all five, correctly
};
$ clang++ -std=c++23 -O2 -Wall -Wextra rule_of_five.cpp -o rule_of_five && ./rule_of_five
b 4, c 4, moved-from a 0; y 4, z 4, moved-from x 0

Thirty lines of careful code against one line (std::vector<float> data;), with the same behaviour: copies get their own buffer, moved-from objects are empty. Write only a destructor and forget the other four, and copying the object gives two owners of one buffer, freed twice: the UB gallery on C++: the essentials shows its "double free" case crash at -O0, and the bug vanish at -O2, where the compiler removed the allocation altogether.

Which special members does the compiler write for a class holding a unique_ptr and a vector?

It generates the destructor, the move constructor and the move assignment (member-wise; noexcept because both members' are). It defines the copy constructor and copy assignment as deleted, because unique_ptr's copy operations are deleted: a member-wise copy is impossible. The class is move-only, like unique_ptr itself. Declaring any of the five yourself (even ~T() = default;) would suppress the implicit moves, and copies would silently take their place where copying is allowed; that is why the rule of zero says declare none. The exact conditions are listed under "Implicitly-declared move constructor" on cppreference.

Problem moves solveCopy-by-default without paying for copies of temporaries and returned values.
What they costThe rules (value categories, noexcept, moved-from states) are the hardest part of the language to learn.
Common mistakesUsing an object after std::move; return std::move(x); a hand-written move constructor without noexcept; moving from const.