Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::launder — a pointer after storage reuse

std::launder from <new> obtains a pointer to an object at a given address when an old pointer does not automatically refer to its replacement. It neither creates an object nor repairs invalid memory access.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <new>

// Inside a function, given a T* p that meets std::launder's preconditions:
T* current = std::launder(p);

std::launder(p) returns a pointer of type T* to an object at the address represented by p. It is useful after storage reuse when lifetime rules prevent using the old pointer as a pointer to the new object. Declared in <new>, it neither allocates storage nor starts an object's lifetime.

T must not be a function type or void. An object whose type is similar to T under the qualification rules must exist at that address. In the ordinary case, it must already be within its lifetime. Every byte reachable through the result must also be reachable through p: the function does not expand the permitted access range. It does not repair misalignment, an incompatible type, or access to deallocated storage.

With transparent replacement, old pointers automatically refer to the new object, so std::launder is unnecessary. The example deliberately replaces a complete const Item in dynamic storage, where that rule does not apply. Do not analogously reuse the storage of a complete const object with automatic, static, or thread storage duration.

In the example, placement new creates the replacement, and std::launder(old) supplies the pointer used for reading and delete. Evaluating old->value directly after replacement would have undefined behavior. Alternatively, retain the pointer returned directly by placement new instead of calling std::launder. The name “pointer optimization barrier” does not mean a thread-synchronization barrier.

Examples

#include <iostream>
#include <new>

struct Item {
    int value;
};

int main() {
    const Item* old = new const Item{3};
    ::new (static_cast<void*>(const_cast<Item*>(old))) const Item{5};

    const Item* current = std::launder(old);
    std::cout << current->value << '\n';
    delete current;
}

Result

5

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources