Is the way C++ structs are laid out set by the standard, or at least common across compilers?
I have a struct where one of its members needs to be aligned on 16 byte boundaries, and this would be easier if I can guarantee the ordering of the fields.
Also, for non-virtual classes, is the address of the first element also likely to be the address of the struct?
I’m most interested in GCC and MSVS.
C and C++ both guarantee that fields will be laid out in memory in the same order as you define them. For C++ that’s only guaranteed for a POD type1 (anything that would be legitimate as a C struct [Edit: C89/90 — not, for example, a C99 VLA] will also qualify as a POD).
The compiler is free to insert padding between members and/or at the end of the struct. Most compilers give you some way to control that (e.g.,
#pragma pack(N)), but it does vary between compilers.1Well, there is one corner case they didn’t think of, where it isn’t guaranteed for a POD type — an access specifier breaks the ordering guarantee:
This is a POD type, but the
public:betweenyandzmeans they could theoretically be re-ordered. I’m pretty sure this is purely theoretical though — I don’t know of any compiler that does reorder the members in this situation (and unless memory fails me even worse than usual today, this is fixed in C++0x).Edit: the relevant parts of the standard (at least most of them) are §9/4:
and §8.5.1/1:
and §9.2/12:
Though that’s restricted somewhat by §9.2/17:
Therefore, (even if preceded by a
public:, the first member you define must come first in memory. Other members separated bypublic:specifiers could theoretically be rearranged.I should also point out that there’s some room for argument about this. In particular, there’s also a rule in §9.2/14:
Therefore, if you have something like:
It is required to be layout compatible with:
I’m pretty sure this is/was intended to mean that the members of the two structs must be laid out the same way in memory. Since the second one clearly can’t have its members rearranged, the first one shouldn’t be either. Unfortunately, the standard never really defines what “layout compatible” means, rendering the argument rather weak at best.