Getting unexpected result when combining [[no_unique_address]] with empty base class inheritance

Viewed 127

Consider following:

struct Base {};

struct Empty {};

struct X : Base {
  int i;
  [[no_unique_address]] Empty e;
};

static_assert(sizeof(X) == 4);

The X inherits the empty Base and gains EBO, and since its member e also uses [[no_unique_address]] attribute, this makes the size of X only the size of the int.

But when I use X as a member variable of another struct Y that inherits an empty Base, the size of Y suddenly becomes 8:

struct Y : Base {
  X x;
  [[no_unique_address]] Empty e;
};

static_assert(sizeof(Y) == 8);

Did Y violate the standard and make EBO banned? Or does this just depend on the implementation of the compiler vendor?

1 Answers

Quoted directly from cppreference:

Empty base optimization is prohibited if one of the empty base classes is also the type or the base of the type of the first non-static data member, since the two base subobjects of the same type are required to have different addresses within the object representation of the most derived type.

Related