# std::launder

> C++ Atlas: `cppatlas.com/w/cpp/utility/launder` | Source: https://en.cppreference.com/w/cpp/utility/launder | Domain: Utility | Standards: C++17

Devirtualization fence with respect to p. Returns a pointer to an object at the same address that p represents, while the object can be a new base class subobject whose most derived class is different from that of the original *p object.

## 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 <new>

template< class T >
constexpr T* launder( T* p ) noexcept; // (since C++17)
```

Devirtualization fence with respect to `p`. Returns a pointer to an object at the same address that `p` represents, while the object can be a new base class subobject whose most derived class is different from that of the original `*p` object.

Formally, given

- the pointer `p` represents the address `A` of a byte in memory
- an object `x` is located at the address `A`
- `x` is within its lifetime
- the type of `x` is the same as `T`, ignoring cv-qualifiers at every level
- every byte that would be reachable through the result is reachable through p (bytes are reachable through a pointer that points to an object `y` if those bytes are within the storage of an object `z` that is pointer-interconvertible with `y`, or within the immediately enclosing array of which `z` is an element).

Then `std::launder(p)` returns a value of type `T*` that points to the object `x`. Otherwise, the behavior is undefined.

The program is ill-formed if `T` is a function type or (possibly cv-qualified) `void`.

`std::launder` may be used in a core constant expression if and only if the (converted) value of its argument may be used in place of the function invocation. In other words, `std::launder` does not relax restrictions in constant evaluation.

### Notes

`std::launder` has no effect on its argument. Its return value must be used to access the object. Thus, it's always an error to discard the return value.

Typical uses of `std::launder` include:

- Obtaining a pointer to an object created in the storage of an existing object of the same type, where pointers to the old object cannot be reused (for instance, because either object is a base class subobject);
- Obtaining a pointer to an object created by placement `new` from a pointer to an object providing storage for that object.

The *reachability* restriction ensures that `std::launder` cannot be used to access bytes not accessible through the original pointer, thereby interfering with the compiler's escape analysis.

```cpp
int x[10];
auto p = std::launder(reinterpret_cast<int(*)[10]>(&x[0])); // OK

int x2[2][10];
auto p2 = std::launder(reinterpret_cast<int(*)[10]>(&x2[0][0]));
// Undefined behavior: x2[1] would be reachable through the resulting pointer to x2[0]
// but is not reachable from the source

struct X { int a[10]; } x3, x4[2]; // standard layout; assume no padding
auto p3 = std::launder(reinterpret_cast<int(*)[10]>(&x3.a[0])); // OK
auto p4 = std::launder(reinterpret_cast<int(*)[10]>(&x4[0].a[0]));
// Undefined behavior: x4[1] would be reachable through the resulting pointer to x4[0].a
// (which is pointer-interconvertible with x4[0]) but is not reachable from the source

struct Y { int a[10]; double y; } x5;
auto p5 = std::launder(reinterpret_cast<int(*)[10]>(&x5.a[0]));
// Undefined behavior: x5.y would be reachable through the resulting pointer to x5.a
// but is not reachable from the source
```

### Example

```cpp
#include <cassert>
#include <cstddef>
#include <new>

struct Base
{
    virtual int transmogrify();
};

struct Derived : Base
{
    int transmogrify() override
    {
        new(this) Base;
        return 2;
    }
};

int Base::transmogrify()
{
    new(this) Derived;
    return 1;
}

static_assert(sizeof(Derived) == sizeof(Base));

int main()
{
    // Case 1: the new object failed to be transparently replaceable because
    // it is a base subobject but the old object is a complete object.
    Base base;
    int n = base.transmogrify();
    // int m = base.transmogrify(); // undefined behavior
    int m = std::launder(&base)->transmogrify(); // OK
    assert(m + n == 3);

    // Case 2: access to a new object whose storage is provided
    // by a byte array through a pointer to the array.
    struct Y { int z; };
    alignas(Y) std::byte s[sizeof(Y)];
    Y* q = new(&s) Y{2};
    const int f = reinterpret_cast<Y*>(&s)->z; // Class member access is undefined
                                               // behavior: reinterpret_cast<Y*>(&s)
                                               // has value "pointer to s" and does
                                               // not point to a Y object
    const int g = q->z; // OK
    const int h = std::launder(reinterpret_cast<Y*>(&s))->z; // OK

    [](...){}(f, g, h); // evokes [[maybe_unused]] effect
}
```

### Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| LWG 2859 | C++17 | definition of *reachable* did not consider pointer arithmetic from pointer-interconvertible object | included |
| LWG 3495 | C++17 | `std::launder` might make pointer to an inactive member dereferenceable in constant expression | forbidden |

## 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/utility/launder (cppreference.com), licensed under CC-BY-SA 3.0 and GFDL. Modified: converted to markdown, study notes added. Offline snapshot of 9 February 2025.