0

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; }, test )

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

Community
  • 1
  • 1
JustMaximumPower
  • 1,257
  • 3
  • 11
  • 22

1 Answers1

3

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
  • 348,265
  • 75
  • 913
  • 977
  • 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 Mar 29 '10 at 14:08
  • @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 Mar 29 '10 at 14:30