c++ - 获取指向结构的第一个元素的指针

标签 c++ pointers struct alignment member

我认为该标准为我提供了一个函数来查找结构的第一个st 元素。不过我好像找不到。

我害怕对齐:我认为将 reinterpret_cast 放入结构的第 1st 元素中是不合法的,对吗?

例如给定 struct { int first, int second } foo;如果我不知道 first 被布置为 1<支持>st 元素? (这意味着 &foo.first 不是有效的解决方案。)

最佳答案

I don't think it's legal to reinterpret_cast into the 1st element of a struct is it?

合法的,但前提是该类是标准布局。标准草案:

[basic.compound]

Two objects a and b are pointer-interconvertible if:

...

  • one is a standard-layout class object and the other is the first non-static data member of that object, or, if the object has no non-static data members, any base class subobject of that object (10.3), or

...

If two objects are pointer-interconvertible, then they have the same address, and it is possible to obtain a pointer to one from a pointer to the other via a reinterpret_cast ...

关于c++ - 获取指向结构的第一个元素的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53836853/

相关文章:

C- 交换结构数组内的字符串或数字的决策函数

c - 如何将一系列整数分配给结构中的指针var

c++ - 识别 WinRT 的宏?

c++ - vector<const int> 是不允许的。为什么 pair<const int, int> 被允许?

将字符转换为整数并将它们添加到 C 中

c - 为什么C程序崩溃?

c - 使用函数增加动态数组大小;无错误,下一个尺寸无效(快)

c++ - C++ 中数组对象的隐式类型转换

c++ - 私有(private)继承和交换

python - struct pack 打印字符串而不是二进制值