On 08/16/2010 06:04 PM, Bruno Haible wrote: > Paolo Bonzini wrote: >>>> #define offsetof(__a,__b) ((size_t)(&(((__a*)0)->__b))) >> In C, the macro will work in practice with all compilers. > > In C++, however, some versions of g++ give a warning or error > if this macro is used for a type that is not a POD type (that is, > a type that has constructors or member functions or similar).
In C++, offsetof is only defined for POD types. So the fact that it gives a warning or error on a non-POD type can be construed a feature. However, there is the nagging issue that under the current C++ standard, a POD struct can still have an operator& which interferes with this approach. http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#273 > I ended up using this definition: > > #if defined __GNUG__ > #define offsetof(type,ident) ((size_t)&(((type*)1)->ident)-1) Which means this definition is not robust for C++. (For that matter, gcc ships with it's own <stddef.h> that provides __builtin_offsetof regardless of host machine, so you don't have to worry about fixing offsetof for gcc.) -- Eric Blake ebl...@redhat.com +1-801-349-2682 Libvirt virtualization library http://libvirt.org
signature.asc
Description: OpenPGP digital signature