如果我有以下结构:
struct Foo { int a; };
下面的代码是否符合 C++ 标准?我的意思是,它不能生成“未定义的行为”吗?
Foo foo;
int ifoo;
foo = *reinterpret_cast<Foo*>(&ifoo);
void bar(int value);
bar(*reinterpret_cast<int*>(&foo));
auto fptr = static_cast<void(*)(...)>(&bar);
fptr(foo);
最佳答案
N3290 中的 9.2/20
A pointer to a standard-layout struct object, suitably converted using a reinterpret_cast, points to its initial member (or if that member is a bit-field, then to the unit in which it resides) and vice versa.
你的 Foo 是一个标准布局类。
所以你的第二次转换是正确的。
我认为不能保证第一个是正确的(而且我使用的架构中 char 比仅包含 char 的结构具有更弱的对齐限制,在这样的架构上,这将是有问题的)。标准保证是,如果你有一个指向 int 的指针,它实际上指向结构的第一个元素,你可以将它重新解释为指向结构的指针。
同样,如果它是一个 reinterpret_cast,我看不到任何东西可以让你的第三个定义(我很确定一些 ABI 使用不同的约定来传递结构和基本类型,所以它非常可疑,我需要一个在标准中明确提到接受它),我很确定在函数指针之间没有任何东西允许 static_cast。
关于c++ - 一个元素的结构是否与元素本身兼容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8970969/