Strict aliasing is a rule stating that accessing an object through a pointer or reference of a different type (that doesn't form a proper subset relationship, like char*) causes undefined behavior. The compiler assumes pointers of different types never point to the same object and optimizes accordingly. Violating this assumption produces incorrect results.
Avoid strict aliasing violations: don't cast pointers between unrelated types to access objects; use std::memcpy or std::bit_cast (C++20) for type-punning.
This example shows a strict aliasing violation and the safe alternative.
// compile: g++ -std=c++20 -O2 -o alias alias.cpp // run: ./alias // description: strict aliasing: incorrect casting vs safe bit_cast #include <iostream> #include <cstring> #include <bit> int main() { int x = 0x12345678; // Unsafe: violates strict aliasing // float* fp = (float*)&x; // float y = *fp; // UB: accessing int via float* // Safe: use std::bit_cast (C++20) float y = std::bit_cast<float>(x); std::cout << "Safely bit-casted: " << y << "\n"; // Safe: use memcpy float z; std::memcpy(&z, &x, sizeof(int)); std::cout << "Via memcpy: " << z << "\n"; return 0; }