开发者

Example where TYPE_ALIGNMENT() fails

开发者 https://www.devze.com 2022-12-25 12:59 出处:网络
I have a question relating to alignment in C/C++. In Determining the alignment of C/C++ structures in relation to its members Michael Burr posted this macro:

I have a question relating to alignment in C/C++. In Determining the alignment of C/C++ structures in relation to its members Michael Burr posted this macro:

#define TYPE_ALIGNMENT( t ) offsetof( struct { char x; t test; 开发者_Python百科}, test )

In the comments someone wrote this might fail with non POD types. Can someone give me an code example where this fails?


offsetof is only specified to work for POD types. If a class contains any data members that are not POD, the class itself is not POD. So, if t in your example is a non-POD type, it is not guaranteed to work.

From the C++ standard (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.

So, if you use offsetof on a non-POD type, the results are undefined.

0

精彩评论

暂无评论...
验证码 换一张
取 消