Say I have a union like this
union blah {
foo f;
bar b;
};
where both foo
and bar
are trivially copyable. Is it safe to do this:
blah b;
foo f;
memcpy(&b, &f, sizeof(f));
and then use b.f
as the active union member? Or, do I have to memcpy to the particular union member, like this:
memcpy(&b.f, &f, sizeof(f));
The reason I'm concerned about this in practice is because I'm about to have to write a function that's roughly like this:
template<int c>
void init_union(blah& b, typename type_family<c>::type const& t) {
switch (c) {
case 0:
memcpy(&b.p0, &t, sizeof(t));
break;
case 1:
memcpy(&b.p1, &t, sizeof(t));
break;
// etc.
}
}
but I would rather be able to skip the whole switch statement and just write this:
template<int c>
void init_union(blah& b, typename type_family<c>::type const& t) {
memcpy(&b, &t, sizeof(t));
}