# std::unique_ptr

> C++ Atlas: `cppatlas.com/w/cpp/memory/unique_ptr` | Source: https://en.cppreference.com/w/cpp/memory/unique_ptr | Domain: Memory management | Standards: C++11, C++14, C++20

std::unique_ptr is a smart pointer that owns (is responsible for) and manages another object via a pointer and subsequently disposes of that object when the unique_ptr goes out of scope.

## Executive Mental Model (Study Companion)

**Core Intuition:** Allocating bytes does not create an object, and freeing bytes is not what destroys one—lifetime begins at initialization and ends at destruction or storage reuse.

- **Standard Era:** C++11 → C++17 → C++20 → C++23
- **Primary ISO Clauses:** [basic.life], [basic.stc], [class.temporary], [stmt.ranged]
- **CppCon Talk Angle:** Show the two timelines side by side: storage duration (how long the bytes exist) vs. object lifetime (when the typed object is legally alive inside those bytes).
- **Common Audience Trap:** Assuming temporary lifetime extension propagates through accessor methods like auto& x = make_container().front(); inside range-for loops.
- **Stage Takeaway:** Use C++20 std::bit_cast instead of pointer-punning reinterpret_cast, and verify C++23 P2718 before trusting chained temporaries in range-for.

## Memory Map Walkthrough: Virtual Address Space & Scope Lifetime Scrubber

In C++, storage duration and object lifetime are distinct concepts. Storage duration governs when raw memory exists—static, thread-local, automatic on the stack, or dynamic on the heap—while object lifetime begins only when initialization completes and ends when the destructor starts or the storage is reused. Binding a temporary directly to a const lvalue reference or rvalue reference extends its lifetime to the reference's scope, but chaining through a member function or accessor stops lifetime extension cold, creating a classic dangling reference before C++23's range-for fix (P2718R0). Meanwhile, placement-new reusing storage that contained const or reference subobjects requires std::launder so the optimizer does not reuse cached values from the previous object.

### Storage duration is not object lifetime ([basic.life] §6.7.3)

When you allocate raw aligned storage (alignas(Widget) std::byte buf[sizeof(Widget)];), storage exists, yet zero Widget objects live there. Accessing a Widget* pointing to buf before placement-new construction is Undefined Behavior.

C++20 softened one long-standing C interop pain point with Implicit-Lifetime Types ([intro.object]): malloc or std::start_lifetime_as (C++23) can implicitly begin the lifetime of trivial aggregates/arrays so C network buffers no longer rely on theoretical UB.

*Why std::launder exists for const members:*
```cpp
struct Node { const int id; };
Node* p = new Node{1};
// Reuse p's storage with placement new:
new (p) Node{2};
// Compiler may legally assume p->id is STILL 1 because 'id' is const!
int safe_id = std::launder(p)->id; // Guaranteed 2 ([ptr.launder])
```

**Key takeaway:** Compilers track pointer provenance and const member immutability; std::launder tells the optimizer a fresh object replaced the old one at that address.

### Temporary lifetime extension & the range-for cliff ([class.temporary] & [stmt.ranged])

Writing const std::string& s = make_name(); extends the materialized temporary string to match s's scope. Write const char* p = make_name().c_str(); or auto& item : get_wrapper().items() in C++11–C++20, and the outer temporary wrapper is destroyed BEFORE the loop body even begins!

C++23 paper P2718R0 finally fixed range-based for loops by extending the lifetime of ALL temporaries in the range-initializer expression until the loop finishes—matching what every developer already assumed.

*Pre-C++23 range-for dangling temporary:*
```cpp
struct Wrapper { std::vector<int> items{1, 2, 3}; };
Wrapper make_wrapper();

// Pre-C++23: UB! Wrapper temporary dies before loop starts!
// C++23 (P2718R0): Well-defined! All temporaries in range-init extend across loop.
for (int v : make_wrapper().items) {
    use(v);
}
```

**Key takeaway:** Whenever a function returns a reference or view into a temporary receiver (std::string_view, std::span, or .items), check whether you are pre-C++23.

## Official Specification Summary (cppreference)

```cpp
// Defined in header <memory>

template<
    class T,
    class Deleter = std::default_delete<T>
> class unique_ptr; // (1) (since C++11)

template <
    class T,
    class Deleter
> class unique_ptr<T[], Deleter>; // (2) (since C++11)
```

`std::unique_ptr` is a smart pointer that owns (is responsible for) and manages another object via a pointer and subsequently disposes of that object when the `unique_ptr` goes out of scope.

The object is disposed of, using the associated deleter, when either of the following happens:

- the managing `unique_ptr` object is destroyed.
- the managing `unique_ptr` object is assigned another pointer via `operator=` or `reset()`.

The object is disposed of, using a potentially user-supplied deleter, by calling `get_deleter()(ptr)`. The default deleter (`std::default_delete`) uses the `delete` operator, which destroys the object and deallocates the memory.

A `unique_ptr` may alternatively own no object, in which case it is described as *empty*.

There are two versions of `std::unique_ptr`:

1. Manages a single object (e.g., allocated with `new`).
2. Manages a dynamically-allocated array of objects (e.g., allocated with `new[]`).

The class satisfies the requirements of *MoveConstructible* and *MoveAssignable*, but of neither *CopyConstructible* nor *CopyAssignable*.

**Type requirements**

- `Deleter` must be *FunctionObject* or lvalue reference to a *FunctionObject* or lvalue reference to function, callable with an argument of type `unique_ptr<T, Deleter>::pointer`.

### Notes

Only non-const `unique_ptr` can transfer the ownership of the managed object to another `unique_ptr`. If an object's lifetime is managed by a `const std::unique_ptr`, it is limited to the scope in which the pointer was created.

`std::unique_ptr` is commonly used to manage the lifetime of objects, including:

- providing exception safety to classes and functions that handle objects with dynamic lifetime, by guaranteeing deletion on both normal exit and exit through exception.

- passing ownership of uniquely-owned objects with dynamic lifetime into functions.

- acquiring ownership of uniquely-owned objects with dynamic lifetime from functions.

- as the element type in move-aware containers, such as `std::vector`, which hold pointers to dynamically-allocated objects (e.g. if polymorphic behavior is desired).

`std::unique_ptr` may be constructed for an incomplete type `T`, such as to facilitate the use as a handle in the pImpl idiom. If the default deleter is used, `T` must be complete at the point in code where the deleter is invoked, which happens in the destructor, move assignment operator, and `reset` member function of `std::unique_ptr`. (In contrast, `std::shared_ptr` can't be constructed from a raw pointer to incomplete type, but can be destroyed where `T` is incomplete). Note that if `T` is a class template specialization, use of `unique_ptr` as an operand, e.g. `!p` requires `T`'s parameters to be complete due to ADL.

If `T` is a derived class of some base `B`, then `std::unique_ptr<T>` is implicitly convertible to `std::unique_ptr<B>`. The default deleter of the resulting `std::unique_ptr<B>` will use operator delete for `B`, leading to undefined behavior unless the destructor of `B` is virtual. Note that `std::shared_ptr` behaves differently: `std::shared_ptr<B>` will use the operator delete for the type `T` and the owned object will be deleted correctly even if the destructor of `B` is not virtual.

Unlike `std::shared_ptr`, `std::unique_ptr` may manage an object through any custom handle type that satisfies *NullablePointer*. This allows, for example, managing objects located in shared memory, by supplying a `Deleter` that defines `typedef boost::offset_ptr pointer;` or another fancy pointer.

| Feature-test macro | Value | Std | Feature |
| --- | --- | --- | --- |
| `__cpp_lib_constexpr_memory` | `202202L` | (C++23) | `constexpr` `std::unique_ptr` |

### Member types

**Member type — Definition**

- `pointer`: `std::remove_reference<Deleter>::type::pointer` if that type exists, otherwise `T*`. Must satisfy *NullablePointer*
- `element_type`: `T`, the type of the object managed by this `unique_ptr`
- `deleter_type`: `Deleter`, the function object or lvalue reference to function or to function object, to be called from the destructor

### Member functions

- (constructor): constructs a new `unique_ptr` (public member function)
- (destructor): destructs the managed object if such is present (public member function)
- `operator=`: assigns the `unique_ptr` (public member function)

**Modifiers**

- `release`: returns a pointer to the managed object and releases the ownership (public member function)
- `reset`: replaces the managed object (public member function)
- `swap`: swaps the managed objects (public member function)

**Observers**

- `get`: returns a pointer to the managed object (public member function)
- `get_deleter`: returns the deleter that is used for destruction of the managed object (public member function)
- `operator bool`: checks if there is an associated managed object (public member function)

**Single-object version, unique_ptr<T>**

- `operator*`, `operator->`: dereferences pointer to the managed object (public member function)

**Array version, unique_ptr<T[]>**

- `operator[]`: provides indexed access to the managed array (public member function)

### Non-member functions

- `make_unique` (C++14), `make_unique_for_overwrite` (C++20): creates a unique pointer that manages a new object (function template)
- `operator==`, `operator!=` (removed in C++20), `operator<`, `operator<=`, `operator>`, `operator>=`, `operator<=>` (C++20): compares to another `unique_ptr` or with `nullptr` (function template)
- `operator<<(std::unique_ptr)` (C++20): outputs the value of the managed pointer to an output stream (function template)
- `std::swap(std::unique_ptr)` (C++11): specializes the `std::swap` algorithm (function template)

### Helper classes

- `std::hash<std::unique_ptr>` (C++11): hash support for `std::unique_ptr` (class template specialization)

### Example

```cpp
#include <cassert>
#include <cstdio>
#include <fstream>
#include <iostream>
#include <locale>
#include <memory>
#include <stdexcept>

// helper class for runtime polymorphism demo below
struct B
{
    virtual ~B() = default;

    virtual void bar() { std::cout << "B::bar\n"; }
};

struct D : B
{
    D() { std::cout << "D::D\n"; }
    ~D() { std::cout << "D::~D\n"; }

    void bar() override { std::cout << "D::bar\n"; }
};

// a function consuming a unique_ptr can take it by value or by rvalue reference
std::unique_ptr<D> pass_through(std::unique_ptr<D> p)
{
    p->bar();
    return p;
}

// helper function for the custom deleter demo below
void close_file(std::FILE* fp)
{
    std::fclose(fp);
}

// unique_ptr-based linked list demo
struct List
{
    struct Node
    {
        int data;
        std::unique_ptr<Node> next;
    };

    std::unique_ptr<Node> head;

    ~List()
    {
        // destroy list nodes sequentially in a loop, the default destructor
        // would have invoked its `next`'s destructor recursively, which would
        // cause stack overflow for sufficiently large lists.
        while (head)
        {
            auto next = std::move(head->next);
            head = std::move(next);
        }
    }

    void push(int data)
    {
        head = std::unique_ptr<Node>(new Node{data, std::move(head)});
    }
};

int main()
{
    std::cout << "1) Unique ownership semantics demo\n";
    {
        // Create a (uniquely owned) resource
        std::unique_ptr<D> p = std::make_unique<D>();

        // Transfer ownership to `pass_through`,
        // which in turn transfers ownership back through the return value
        std::unique_ptr<D> q = pass_through(std::move(p));

        // p is now in a moved-from 'empty' state, equal to nullptr
        assert(!p);
    }

    std::cout << "\n" "2) Runtime polymorphism demo\n";
    {
        // Create a derived resource and point to it via base type
        std::unique_ptr<B> p = std::make_unique<D>();

        // Dynamic dispatch works as expected
        p->bar();
    }

    std::cout << "\n" "3) Custom deleter demo\n";
    std::ofstream("demo.txt") << 'x'; // prepare the file to read
    {
        using unique_file_t = std::unique_ptr<std::FILE, decltype(&close_file)>;
        unique_file_t fp(std::fopen("demo.txt", "r"), &close_file);
        if (fp)
            std::cout << char(std::fgetc(fp.get())) << '\n';
    } // `close_file()` called here (if `fp` is not null)

    std::cout << "\n" "4) Custom lambda-expression deleter and exception safety demo\n";
    try
    {
        std::unique_ptr<D, void(*)(D*)> p(new D, [](D* ptr)
        {
            std::cout << "destroying from a custom deleter...\n";
            delete ptr;
        });

        throw std::runtime_error(""); // `p` would leak here if it were a plain pointer
    }
    catch (const std::exception&)
    {
        std::cout << "Caught exception\n";
    }

    std::cout << "\n" "5) Array form of unique_ptr demo\n";
    {
        std::unique_ptr<D[]> p(new D[3]);
    } // `D::~D()` is called 3 times

    std::cout << "\n" "6) Linked list demo\n";
    {
        List wall;
        const int enough{1'000'000};
        for (int beer = 0; beer != enough; ++beer)
            wall.push(beer);

        std::cout.imbue(std::locale("en_US.UTF-8"));
        std::cout << enough << " bottles of beer on the wall...\n";
    } // destroys all the beers
}
```

Possible output:

```text
1) Unique ownership semantics demo
D::D
D::bar
D::~D

2) Runtime polymorphism demo
D::D
D::bar
D::~D

3) Custom deleter demo
x

4) Custom lambda-expression deleter and exception safety demo
D::D
destroying from a custom deleter...
D::~D
Caught exception

5) Array form of unique_ptr demo
D::D
D::D
D::D
D::~D
D::~D
D::~D

6) Linked list demo
1,000,000 bottles of beer on the wall...
```

### See also

- [`shared_ptr`](https://en.cppreference.com/w/cpp/memory/shared_ptr) (C++11): smart pointer with shared object ownership semantics (class template)
- [`weak_ptr`](https://en.cppreference.com/w/cpp/memory/weak_ptr) (C++11): weak reference to an object managed by `std::shared_ptr` (class template)

## Podcast Host Debate & Socratic Standard Traps

Use the prompts and tricky ISO standard questions below to guide a Socratic audio discussion:

- Contrast raw storage duration with actual C++ object lifetime—and why malloc doesn't invoke constructors.
- Walk through why range-based for loops with temporary wrappers dangled for 12 years until C++23 P2718.
- Explain why strict aliasing breaks pointer-punning casts and how std::bit_cast solves it cleanly.

### Trap 1: [stmt.ranged] & P2718R0 (cppcon-stage)

Under C++17/C++20 rules, what happens in for (int x : make_holder().vec) if make_holder() returns a Holder by value?

```cpp
struct Holder { std::vector<int> vec{1, 2, 3}; };
Holder make_holder();
for (int x : make_holder().vec) { /* ... */ }
```

A. Safe in C++17 because the range-for __range reference extends Holder
B. Undefined behavior in C++17/C++20 because __range binds to .vec, leaving the Holder temporary to die before the loop body
C. Does not compile because vector cannot be copied
D. Extends Holder only when using auto&& x

**Standard Answer (B):** Undefined behavior in C++17/C++20 because __range binds to .vec, leaving the Holder temporary to die before the loop body

**Why:** In C++11–C++20, the range-for desugaring binds auto&& __range = make_holder().vec;. Because __range binds to the member subobject rather than the whole Holder temporary, the Holder temporary is destroyed at the semicolon of the __range declaration! C++23 (P2718R0) patched this rule specifically for range-for.

*CppCon speaker note:* One of the most famous real-world C++ bugs—even standard committee members tripped on it.

### Trap 2: [basic.life] & [ptr.launder] (standard-lawyer)

After destroying and placement-new constructing a struct containing a const int member in the same storage, how must you access the new object through the old pointer p?

```cpp
struct X { const int n; };
X* p = new X{1};
p->~X();
new (p) X{2};
```

A. p->n directly is always valid once placement new completes
B. std::launder(p)->n is required because X contains a const non-static data member
C. reinterpret_cast<X*>(p)->n avoids the requirement
D. Reusing storage containing a const member is impossible even with std::launder

**Standard Answer (B):** std::launder(p)->n is required because X contains a const non-static data member

**Why:** [basic.life]/8 states an old pointer automatically refers to the new object ONLY if the type has no const or reference non-static data members (among other rules). Otherwise, you must obtain the new pointer via placement new's return value or std::launder(p).

### Trap 3: [stmt.jump] & [class.dtor] (subtle)

In a single block { Guard a; Guard b; }, in what order are destructors invoked upon normal exit or an exception thrown after b is constructed?

A. a then b (construction order)
B. b then a (strict reverse order of construction)
C. Unspecified by the standard
D. Destructors are skipped if an exception unwinds

**Standard Answer (B):** b then a (strict reverse order of construction)

**Why:** Automatic local objects and class member subobjects are ALWAYS destroyed in exact reverse order of construction completion (LIFO), enabling dependent RAII guards like b holding a handle into a.

### Trap 4: [basic.lval] §7.2.1/11 & [bit.cast] (standard-lawyer)

Which method inspects the IEEE-754 bit pattern of a float as a uint32_t without violating C++ strict aliasing rules?

```cpp
float f = 3.14f;
```

A. uint32_t bits = *reinterpret_cast<uint32_t*>(&f);
B. union Pun { float f; uint32_t u; } p{f}; uint32_t bits = p.u;
C. auto bits = std::bit_cast<uint32_t>(f);
D. *(uint32_t*)(void*)&f

**Standard Answer (C):** auto bits = std::bit_cast<uint32_t>(f);

**Why:** Reading a float through a uint32_t* via reinterpret_cast violates strict aliasing ([basic.lval]), and reading an inactive union member is UB in C++ (unlike C99). C++20 std::bit_cast<uint32_t>(f) (or std::memcpy pre-C++20) is completely well-defined and constexpr.

---
Attribution: content from https://en.cppreference.com/w/cpp/memory/unique_ptr (cppreference.com), licensed under CC-BY-SA 3.0 and GFDL. Modified: converted to markdown, study notes added. Offline snapshot of 9 February 2025.