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?
language-lawyer
tag, which is customary for this kind of question. Since there's a max of five tags, I pickedstd
to remove for that. – Silverts=
? – Cothurnusmemcpy
. – KrimmerTestA
andTestB
, one with a memberfunction_p
and the other one withfunction_p_c
instead. - You say that you want to do it "without some flag-of-active-union-member". If you don't have that kind of flag, how are you going to use the correct funtion pointer at other places in the class? – Downall