views:

49

answers:

1

Hi,

I have a question relating to alignment in c/c++. In http://stackoverflow.com/questions/364483/determining-the-alignment-of-c-c-structures-in-relation-to-its-members Michael Burr posted this Makro:

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

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

+1  A: 

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.

James McNellis
well yes but thats not what I asked. For example class foo{ int i; virtual void bar(){ }};int main(){ std::cout << TYPE_ALIGNMENT(foo) << std::endl; return 0;}works fine (8 on Linux x86-64 with GCC 4.4.3) and as I understand undefined there are at least some cases where it does not work. Or is my understanding of undefined wrong?
JustMaximumPower
@JustMaximumPower: "Works fine" (or, at least appearing to work fine) is a reasonable outcome for something that is undefined. "Crashes horribly" is another reasonable outcome. _Anything_ can happen. Whether it appears to work or it causes pernicious bugs in your software is entirely implementation-dependent. It would be unwise to assume that it works for non-POD types.
James McNellis