When a union object is copied, is a member subobject created?

瘦欲@ 提交于 2019-12-22 08:40:08

问题


When another member of a union is accessed, the C++ standard used to be silent on what happens, but that was fixed to explain that member access to a union object was allowed for the purpose of assigning to that yet no existent object, which would magically create the object, by assignment to it or one of its members. Essentially the member access operator returns a promise of a future object and you have to use it with an assignment.

Given

union U {
  int i;
  long l;
};

We can create a i or l member subobject by assignment:

U u;
u.i = 2; // creates an int
u.l = 3; // creates a long (destroys the int)

But what happens when the union object is copied? How would the compiler "know" which member to "create"?

U u1, u2;
fill(&u1);
u2 = u1; // which u2 member is created here?

When using memcpy on a union from a buffer of bytes filled with numerical values (not filled from another union object), which member becomes "active"?

char buf[sizeof(U)] = { ... };
U u;
memcpy(&u, buf, sizeof u);

来源:https://stackoverflow.com/questions/59232007/when-a-union-object-is-copied-is-a-member-subobject-created

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!