Why does using reinterpret_cast to convert from char * to structure seem to work fine?

People say that it is not good to trust reinterpret_castto convert from raw data (for example char*) into a structure. For example, for structure

struct A
{
    unsigned int a;
    unsigned int b;
    unsigned char c;
    unsigned int d;
};

sizeof(A) = 16and __alignof(A) = 4as 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->aequals 1, ptr->bequals 2, ptr->cequals 3, and ptr->dequals 4.
Well, it seems to work. Exactly what I expected.

But the data pointed to ptrare not aligned by 4 bytes, for example A. What problems can occur on the x86 or x64 platform? Performance issues?

+4
2

, , . endian, . ( .)

"\ x00\x00\x00\x01\x00\x00\x00\x02\x03\x00\x00\x00\x00\x00\x00\x04".

, , .

+ 1 , , .

, (, x86), , . ( . : fooobar.com/questions/9636/...)

, , , C ++ , , . (, -, , .) -, , , , . , data + 1, , , 4 , a = 1, b = 0, c = 0 d = 0.

+3

, , , Visual Studio .. .

, , " ". - .

, , , " ++ ", : reinterpret_cast - , . .

, , ,

  • struct A
  • reinterpret_cast char s

:

  • struct A
  • reinterpret_cast char s
  • reinterpret_cast struct A
0

All Articles