Search code examples
c++strict-aliasing

C++: Casting from char pointer to struct pointer without committing undefined behavior


struct S { char A; char B; char C; char D; };
unsigned char x[4] = { 0xDE, 0xAD, 0xBE, 0xEF };
auto y = (S*) x;
cout << y->A; // undefined behaviour

The fourth line here violates strict aliasing, which means that the compiler could decide to play some mean tricks on me. Is there any way to achieve something similar without invoking undefined behaviour?


Solution

    • Casting and dereferencing is undefined behavior.
    • Union casting is kosher... in C. In C++ it's undefined behavior.
    • reinterpret_cast is undefined behavior.

    The only legit approach is memcpy. A sufficiently smart compiler will optimize it into nothingness, but you really have no guarantees.