c++ - 一个元素的结构是否与元素本身兼容?

标签 c++ c++11

如果我有以下结构:

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/

相关文章:

c++ - sdl_net udp 服务器设置

c++ - C++11编译器的构造函数继承产生错误

c++ - std::set::find 的可读替代品

c++ - ifstream 和 ofstream 中的 filebuf

c++ - 超出 C++ 最大整数数据类型

c++ - opengl c++ 代码中的错误,可能与 cood 系统有关

c++ - 通过转发构造函数参数构建基于可变参数模板的mixin

c++ - 与自定义对象一起使用 accumulate

c++ - 为什么类中的 C 样式数组没有用户定义的运算符 = 支持深度复制

c++ - C++0x 标准如何定义 C++ Auto 多重声明?