Type Punning in C++17: Avoiding Pun-defined Behavior
summary
C++17 rules which type-punning idioms are undefined and which are tolerable: the talk shows that casting between unrelated pointers or mutating non-mutable consts is UB, while conversions round-tripping via integer types are implementation-defined and access via unsigned char or std::byte is permitted. It examines unions (common initial sequence allowed; non-active member access is UB), recommends memcpy as the practical workaround (standard wording is fuzzy), discusses std::launder() for placement-new cases, and measures clang -O3 output (memcpy/REINTERPRET and union variants produce similar tight assembly; the char-based form costs one extra instruction).
AI-written summary · about
chapters (13)
- 0:00Introduction to type punning
- 1:26What is type punning
- 3:11Why type pun and risks involved
- 6:14Trivially copyable types
- 12:30Behavior types in C++
- 23:21Undefined behavior explained
- 24:29Casting away const
- 31:14Pointer to integer conversions
- 40:23Accessing value representations
- 45:15Reinterpret cast and strict aliasing
- 52:17Type punning with unions
- 56:46Punning with unrelated types
- 1:03:33Summary and best practices
related talks
01h 00mType punning in modern C++
04mAliasing Redefined
59mA Tour of C++ Recognised User Type Categories
54mTypical C++, But Why?
05mThe dangers of C-style casts
30mC++ Cryptozoology - A Compendium of Cryptic Characters :: #2
01h 19mThis is C++: Uncompromised Performance, Undefined Behavior, & Move Semantics
51mTypical C++, but Why?
