有人说使用reinterpret_cast
将原始数据(如char*
)转换为结构体是不好的。例如,对于以下结构体:
struct A
{
unsigned int a;
unsigned int b;
unsigned char c;
unsigned int d;
};
sizeof(A) = 16
,__alignof(A) = 4
,正如预期的那样。
假设我这样做:
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
然后将一些数据复制到ptr
:
memcpy_s(sh, sizeof(A),
"\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00", sizeof(A));
然后
ptr->a
是1,ptr->b
是2,ptr->c
是3,ptr->d
是4。好的,看起来能用。正是我所期望的。
但是
ptr
指向的数据并不像应该的A
那样对齐到4字节。这可能会在x86或x64平台上引起什么问题?会有性能问题吗?