People say it's not good to trust reinterpret_cast
to convert from raw data (like char*
) to a structure. For example, for the structure
struct A
{
unsigned int a;
unsigned int b;
unsigned char c;
unsigned int d;
};
sizeof(A) = 16
and __alignof(A) = 4
, exactly as expected.
Suppose I do this:
char *data = new char[sizeof(A) + 1];
A *ptr = reinterpret_cast<A*>(data + 1); // +1 is to ensure it doesn't points to 4-byte aligned data
Then copy some data to ptr
:
memcpy_s(sh, sizeof(A),
"\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00", sizeof(A));
Then ptr->a
is 1, ptr->b
is 2, ptr->c
is 3 and ptr->d
is 4.
Okay, seems to work. Exactly what I was expecting.
But the data pointed by ptr
is not 4-byte aligned like A
should be. What problems this may cause in a x86 or x64 platform? Performance issues?