Can a C++ compiler re-order elements in a struct

It normally can’t reorder elements, no.

An exception is if there’s an access specifier separating them:

struct Foo {    
  A a;
  B b;
  C c;
private:
  D d;
  E e;
  F f;
};

a, b and c are guaranteed to be stored in this order, and d, e and f are guaranteed to be stored in order. But there is no guarantees about where a, b and c are stored relative to d, e and f.

Another thing to keep in mind is that the compiler can insert as much padding as it likes, even if it doesn’t reorder anything.

Here’s the relevant part of the standard:

Section 9.2.12:

Nonstatic data members of a
(non-union) class declared without an
intervening access-specifier are
allocated so that later members have
higher addresses within a class
object. The order of allocation of
nonstatic data members separated by an
access-specifier is unspecified
(11.1)”

Leave a Comment