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 oftype
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.
精彩评论