Reputation: 6570
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?
Upvotes: 0
Views: 523
Reputation: 6570
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.
Upvotes: 1