gpt4 book ai didi

c++ - TYPE_ALIGNMENT() 失败的示例

转载 作者:太空宇宙 更新时间:2023-11-04 07:42:22 24 4
gpt4 key购买 nike

我有一个关于 C/C++ 对齐的问题。在 Determining the alignment of C/C++ structures in relation to its members Michael Burr 发布了这个宏:

#define TYPE_ALIGNMENT( t ) offsetof( struct { char x; t test; }, test )

在有人写的评论中,这可能会因非 POD 类型而失败。有人可以给我一个失败的代码示例吗?

最佳答案

offsetof 仅指定用于 POD 类型。如果一个类包含任何不是 POD 的数据成员,那么该类本身就不是 POD。因此,如果您的示例中的 t 是非 POD 类型,则不能保证它可以正常工作。

来自 C++ 标准 (18.1/5):

The macro offsetof accepts a restricted set of type arguments in this International Standard. type shall be a POD structure or a POD union.

因此,如果您在非 POD 类型上使用 offsetof,则结果是未定义的。

关于c++ - TYPE_ALIGNMENT() 失败的示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2537947/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com