What is the strict aliasing rule and how can violating it cause UB?
Short answer
Strict aliasing says you generally may not access an object through a pointer/reference of an incompatible type (with some exceptions like char/std::byte).
Advertisement
AModel answer
Strict aliasing says you generally may not access an object through a pointer/reference of an incompatible type (with some exceptions like char/std::byte). Violating it—e.g., reinterpreting a float* as an int* and reading through it—is UB, and compilers optimize assuming differently-typed pointers don't alias. Use std::bit_cast, memcpy, or unions carefully to reinterpret bytes safely.
float f=1.0f;
int i = *reinterpret_cast<int*>(&f); // strict-aliasing UBReal-world example
A hand-rolled float-to-int bit hack breaks under optimization due to strict aliasing; std::bit_cast fixes it.
Likely follow-ups
- How do you legally reinterpret bytes? | Why do compilers assume no aliasing?
Related topics