Important clarification: some commenters seem to think that I am copying from a union. Look carefully at the memcpy, it copies from the address of a plain o
memcpy(&u.x_in_a_union, &x); // same types, so should be OK?
std::cout << u.x_in_a_union; // OK here? What's the active member?|
I am 99% sure that the first line is undefined behavior if x_in_a_union is inactive because you cannot take the address of an object that does not exist on the abstract machine. On the abstract machine, pointers are not just addresses but point specifically to objects, and using them is only valid during the lifetime of that object.
Inactive union members do not exist as objects, only one member object of the union is active, exactly during the lifetime of that member object.
There are only 4 ways to create an object,
An object is created by a definition (6.1), by a new-expression(8.3.4), when implicitly changing the active member of a union (12.3), or when a temporary object is created (7.4, 15.2) [intro.object]
and memcpy is not among them.
Probably more importantly, nowhere in the standard description of unions is memcpy mentioned as a way of implicitly changing an active member, it only gives this power to assignment operations, when they are used with an inactive member.
That being said, gcc allows type punning of union types, i.e. it allows accessing inactive types in a well-defined way, but that is not strictly speaking C++.