Thomas Tutone wrote:
.....
Since this a POD struct, it needs to be layout compatible with C. C
requires that the elements appear in the order listed in the
declaration. Letting a C++ compiler rearrange the elements would
therefore break compatibility with C.
Why does C have that requirement? Ask in a C newsgroup.
I think it's topical here (IMHO).
The first C++ compiler (and still many compilers) use a C++ front-end to
a C compiler, so layout rules for data structures were sort of "designed
into" the standard.
C has a "poor man's" type of inheritance. If the compiler re-ordered
struct members it would make it almost impossible to do that. IIRC,
alignment padding was not an issue in the first incantations of the C
compiler. The first C compiler I used I don't believe did any alignment
padding. So to maintain compatability with code written on systems
where alignment padding was not needed, a rule like the one currently in
the standard had to be enforced, otherwise a whole bunch of code would
break.
So, nothing stops you from ordering the members in your struct in a
better way. You may be constrained however.
e.g. (A made-up example use your imagination).
struct A
{
A( B * foo, C * zoo )
: m_btype( B->ComputeBtype( zoo ) ),
m_xtype( new X( m_btype ) ),
m_ytype( new Y( zoo->Fetch( m_btype ) )
{
}
char m_btype;
X * m_xtype;
Y * m_ytype;
char m_code[3];
};
In this case, if you move m_btype, your're introducing a bug.