std::launder: the most obscure new feature of C++17

submited by
Style Pass
2024-04-02 08:30:02

Proposal P0137R1 introduces a new function into the C++ standard library called std::launder. Unfortunately, this proposal is hard to understand for mere mortals.

Don’t ask. If you’re not one of the 5 or so people in the world who already know what this is, you don’t want or need to know.

Here we first initialize u with 1 (so x.n is set to 1, and x becomes the active member of the union). Next, 5 is assigned to u.f and f becomes active. Finally, we do a placement new and overwrite u with the new value 2. The problem here is that n is const-qualified and the optimizer is allowed to assume that it will always remain equal to 1. So, std::launder acts as an optimization barrier that prevents the optimizer from performing constant propagation.

Alisdair Meredith also briefly mentions a real-life use case in his talk “C++17 in Breadth” from CppCon 2016. He tells us that this function might be handy when dealing with containers of const-qualified elements.

Leave a Comment
Related Posts