【发布时间】:2015-05-15 04:43:46
【问题描述】:
人们说信任 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 平台中导致什么问题?性能问题?
【问题讨论】:
-
您想知道是否可以保证特定编译器上的无效 C++ 代码可以正常工作?
-
没有看到微软的源代码,没有人能回答这个问题。
-
@NeilKirk 我想知道的是由于未对齐的结构数据可能会出现什么问题。
-
@NeilKirk 很抱歉,这段代码在 gcc、borland 和 intel 以及 msvc 上为我编译。
-
@Alegnem 我没有说它没有编译。
标签: c++ struct reinterpret-cast