I'm worried about undefined behavior. Can you initialize the value of a trivially copyable union type by using a memcpy? This came up when I considered using Boost Serialization with BOOST_IS_BITWISE_SERIALIZABLE(MyUnionType), which I assume uses something like memcpy.
#include <cstring>
enum class Foo: int {};
union Bar {
int num;
Foo foo;
};
int baz(int src) {
Bar dst;
// My understanding is that memcpy does initialize dst
// but doesn't set the active member of the union.
std::memcpy(&dst, &src, sizeof(Bar));
// My understanding is that whichever member is read
// first here becomes the active member of the union.
if (src > 42) {
return dst.num;
} else {
return (int)dst.foo;
}
}