问题
When another member of a union is accessed, the C++ standard used to be silent on what happens, but that was fixed to explain that member access to a union object was allowed for the purpose of assigning to that yet no existent object, which would magically create the object, by assignment to it or one of its members. Essentially the member access operator returns a promise of a future object and you have to use it with an assignment.
Given
union U {
int i;
long l;
};
We can create a i
or l
member subobject by assignment:
U u;
u.i = 2; // creates an int
u.l = 3; // creates a long (destroys the int)
But what happens when the union object is copied? How would the compiler "know" which member to "create"?
U u1, u2;
fill(&u1);
u2 = u1; // which u2 member is created here?
When using memcpy
on a union from a buffer of bytes filled with numerical values (not filled from another union object), which member becomes "active"?
char buf[sizeof(U)] = { ... };
U u;
memcpy(&u, buf, sizeof u);
来源:https://stackoverflow.com/questions/59232007/when-a-union-object-is-copied-is-a-member-subobject-created