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";
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.
8
u/coachkler Apr 04 '24
I was just looking at this a while ago. I didn't figure it out though