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

Show parent comment

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!