(I just realized I first need to solve a much more basic issue with copying unions: When a union object is copied, is a member subobject created?. Please see that other question first.)
The implicitly generated copy operations (constructor and assignment) of a class perform member by member copy (initialization or assignment). (For a trivial type these are the same.)
So a class with some members not initialized cannot be copied, as accessing uninitialized objects is illegal.
struct C {
int m1, m2;
};
void f() {
C c1, c2;
c1.m1 = 1;
c2 = c1; // not initialized
}
But a union can always be copied, even if it contains class members, some of which aren't initialized (because... by definition not two members of a unions are initialized).
Does that mean that copying a union of a class with uninitialized members is legal:
union U {
C m;
};
void g() {
U u1, u2;
u1.m.m1 = 1;
u2 = u1;
}
and if so, can classes be copied by casting to such union?
void f2() {
C c1, c2;
c1.m1 = 1;
(U&)c2 = (U&)c1; // not initialized?
}
(union U&)c1 = (union U&)c2;
in order to doc1 = c2;
avoiding callingoperator=
when some members aren't initialized. – Cofferdamunion foo foo1, foo2;
foo1.member = foo2.member;
– Osierstd::variant
, with well-defined semantics in this area. – Elizebethelizondoclass
" you beg the question: isclass
unsafe? You say copying a class is illegal if some members are uninitialized, but I think this remarkable claim requires more proof. Admittedly the standard has failed to fully account for this scenario, but I don't think it really says there's UB here. – Contemporaneousmemcpy
of the class directly would be allowed. I think that question comes down to essentially the same as yours, because the implicitly-defined union copy assignment is defined to copy the object representation, effectively doing the same asmemcpy
. – Actinopodm2(other.m2)
in the initializer-list. Would you not consider this to require evaluation ofother.m2
to the indeterminate value? – Actinopodunsigned char
? – Gulch