I'm not quite sure about standard quotes about memcpy
and union
trivial members.
Consider the code:
struct Test{
union
{
void(*function_p)(void*);
void(*function_p_c)(const void*);
};
Test(const Test &other)
{
using std::memcpy;
memcpy(&function_p, &other.function_p, sizeof(function_p)); //?
memcpy(&function_p_c, &other.function_p_c, sizeof(function_p_c)); //??
}
};
int main(void)
{
Test t1; t1.function_p = NULL; //let it be NULL for c++98 sake
Test t2(t1); // is it safe? does this set new active member of union?
return 0;
}
So the one question leads to another:
is code above safe? or is it UB with second/first
memcpy
depending on whichunion
member user have touched? is it overkill to callmemcpy
for both members?if it is not safe then how could I implement copy constructor without some flag-of-active-union-member?