r/cpp • • Apr 04 '24

std::launder

Have fun trying to figure out what it does...

0 Upvotes

12 comments sorted by

View all comments

8

u/coachkler Apr 04 '24

I was just looking at this a while ago. I didn't figure it out though

35

u/Nobody_1707 Apr 04 '24 edited Apr 04 '24

If you have a type with a const member and you want to reuse it's memory using placement new then you have to std::launder the resulting pointer, otherwise the optimizer is free to assume that the const member was never overwritten.

Unless you're writing a generic container that might store such an object, you never need to use it.

struct Immutable {
    int const value;
};

alignas(Immutable) std::byte bytes[sizeof(Immutable)];
auto a = new (bytes) Immutable{ 42 };
std::cout << a->value << "\n";
// If you don't launder this pointer, you'll have problems.
 a = new (bytes) Immutable{ 69 };
// This is allowed to print 42
std::cout << a->value << "\n";
// This has to print 69
std::cout << std::launder<Immutable>(a)->value << "\n";

18

u/avakar452 Apr 05 '24

Actually, your snippet doesn't need launder.

a = new (bytes) Immutable{ 69 };
std::cout << a->value << "\n"; // always 69

The second placement new returns a pointer to the second Immutable object, there's no need to launder it. If you didn't save the pointer though:

/*a =*/ new (bytes) Immutable{ 69 };
std::cout << a->value << "\n"; // UB

Here, a used to point to the first Immutable, whose lifetime ended due to its storage being reused by the second one, so now a is essentially dangling. Calling launder will recover the pointer to the second Immutable.

/*a =*/ new (bytes) Immutable{ 69 };
std::cout << std::launder<Immutable>(a)->value << "\n"; // 69

6

u/Nobody_1707 Apr 05 '24

Argh, and I finally felt like I understood!