In the union U
below, if a
or b
is the active member, is it defined behavior to access c
?
struct A{
int a;
};
struct B{
int a;
double b;
};
union U{
A a;
B b;
int c;
};
In [class.union], the standard defines some rules to make using a union
easier (emphasis mine):
[ Note: One special guarantee is made in order to simplify the use of unions: If a standard-layout union contains several standard-layout structs that share a common initial sequence, and if a non-static data member of an object of this standard-layout union type is active and is one of the standard-layout structs, it is permitted to inspect the common initial sequence of any of the standard-layout struct members; see [class.mem]. — end note ]
I'm hung up on the word struct here. Does a standard layout scalar like int
count even though it's not a struct?
My
union U
above is indeed a "standard-layout" union following [class] that basically says it needs to be a standard layout class that uses theunion
keyword instead, and since we only use scalars (standard layout types), it passes.The structs obviously share a common initial sequence that consists of the first
int
member, but it's unclear if fundamental types can be considered for common initial sequences.- [class.union] also says that "Each non-static data member is allocated as if it were the sole member of a struct." which I think gives evidence that it is defined.
- Finally, standard layout structs are not allowed to have padding at the beginning ([class.mem]), and the members of a union are pointer interconvertible so the standard is telling us that the
int
elements in the standard layout structs, and the non-staticint c
in the union are guaranteed to align.