I was just playing around with g++, and I found that
#include <type_traits>
class Foo {
public: int x;
public: char y;
public: double z;
};
static_assert(std::is_standard_layout<Foo>::value, "Foo is not standard layout");
int main() {}
Compiles just fine.
According to this answer, data members across access specifiers may be reordered in memory
. So there's no gaurantee that x
has to actually be the first member of Foo
when actually laid out in memory. The way I've defined Foo
, y
could actually be the first element right?
I thought standard layout meant that you could more or less understand how the bytes are laid out for the given type. Allowing fields in a standard layout type to be reordered in an arbitrary manner seems counterintuitive to me. Why is this allowed?
All members of your structure have the same access specifier: public
. The fact that the keyword appears before every class member is immaterial. This is equivalent to the public
access specifier appearing once, before all class members.