Rules
-
The union is only as big as necessary to hold its [largest data] member.
-
The other data members are allocated in the [same bytes] as part of that [largest member].
-
The details of that allocation are [implementation-defined], and it’s [undefined behavior] to read from the member of the union that [wasn’t most recently written].
-
Many compilers implement, as a [non-standard language extension], the ability to [read inactive] members of a union.
1 |
|
output
1 |
s.n = 12345678 |
Member allocating
Each member is allocated as if it is the only member of the class.
Conctors and Dectors of members
If members of a union are classes with [user-defined constructors] and [destructors], to switch the active member, [explicit destructor] and [placement new] are generally needed:
1 |
|
output
1 |
s.str = Hello, world |
Member lifetime
1 |
union A { int x; int y[4]; }; |
Anonymous unions
1 |
int () |
Union-like classes
A union-like class is either a (non-union) class that has at least one anonymous union as a member or a union. A union-like class has a set of variant members:
-
the non-static data members of its member anonymous unions;
-
in addition, if the union-like class is a union, its non-static data members that are not anonymous unions.
Union-like classes can be used to implement tagged unions.
1 |
|
output
1 |
a |
近期评论