Type Punning in C++17: Avoiding Pun-defined Behavior
Type punning, treating a type as though it is a different type, has a long and sordid history in C and C++. But, as much as we'd like to deny its existence, it plays an important role in efficient low-level code. If you've ever written a program that examines the individual bits of a pointer or of a floating point number, then you've done type punning. Given its long legacy, some of the techniques for type punning that were appropriate, even encouraged, earlier in history now live in the realm of undefined behavior. We'll identify which techniques are now proscribed and postulate why. We'll also explore ways to do type punning in C++17 that sidestep undefined behavior and are hopefully as efficient as the older techniques. In this session we will look at: o Common (and some uncommon) motivations for type punning. o Techniques for type punning, both good and bad, all ugly. o Related topics (like type conversions and std::launder()) with an eye toward unspecified and undefined behavior.