Type punning in modern C++
summary
Compares concrete techniques — reinterpret_cast and unions cause undefined behaviour; memcpy is the portable fix — using the Quake fast inverse‑sqrt as a concrete example; shows clang, GCC and MSVC all generate identical optimized code when memcpy replaces UB casts. Explains why: strict‑aliasing, alignment and object‑lifetime rules; highlights C++20’s bit_cast (constexpr) and the proposed start_lifetime_as wording plus a future layout‑as attribute to make several remaining patterns safe.
AI-written summary · about
chapters (13)
- 0:00Start
- 1:52Type Padding
- 2:36Code Example
- 5:21Type Planning
- 8:04Reinterpret Casts
- 8:22Undefined Behavior
- 16:37Compile Explorer
- 20:23Strict Agassiz
- 20:48Object Lifetime Rules
- 24:59Create an Object
- 27:17Object Types Have Alignment Requirements
- 29:21Line Storage
- 58:24When You'Re Tight Punting between a Tau or between a Kerr Buffer and a Widget Is It Defined Behavior To Put both into a Union and Mem Copy from What Union Member to the Other Sorry To Put What into a Union and Put both the T and the You into the Union and Use the Mem Copy Technique To Copy from One Union Member to the Other All Right So if You Have these Kind of Unions and We Have this Other Rule That I Didn't Talk about Which Is the Common Initial Sequence Rule Depending on What You'Re Doing You Might Be Able To Get this to Work Let's Look at some Codes
related talks
01h 05mType Punning in C++17: Avoiding Pun-defined Behavior
04mAliasing Redefined
57mIntroduction to C++ Template Metaprogramming
31mCo- and Contra-: Adding a Little Variance
46m“My Little Optimizer: Undefined Behavior is Magic"
49m“Which Machine Am I Coding To?”
01h 41mC++ Type Erasure Demystified
07mISO/IEC 14882
