考虑一个带有改变的“活跃成员”的简单 union :
union U {
int i;
char *p;
};
U u = { 1 };
u.p = 0;
C++ 标准是否有任何修订可以正确定义这里发生的事情?
特别是,u.p
在语义上是什么?它在编译时是一个左值,但它的求值在运行时指的是什么?
u
中的指针对象在被赋值之前是否存在?
对象可以在其生命周期开始之前就存在吗?
两个标量对象(不同类型)能否同时存在于同一地址?
最佳答案
u.p
是指为生命周期尚未开始的对象分配的存储空间,如 [basic.life]/7 所允许的那样: “在对象的生命周期开始之前,但在分配对象将占用的存储空间之后......可以使用引用原始对象的任何泛左值,但只能以有限的方式使用。”
然后有一个特殊的魔法,通过它对 union 成员的赋值开始对象的生命周期:
[class.union]/5 When the left operand of an assignment operator involves a member access expression ([expr.ref]) that nominates a union member, it may begin the lifetime of that union member, as described below...
In an assignment expression of the form
E1 = E2
that uses either the built-in assignment operator ([expr.ass]) or a trivial assignment operator ([class.copy.assign]), for each elementX
ofS(E1)
, if modification ofX
would have undefined behavior under [basic.life], an object of the type ofX
is implicitly created in the nominated storage; no initialization is performed and the beginning of its lifetime is sequenced after the value computation of the left and right operands and before the assignment.
关于c++ - 在 C++ 的任何修订版中,是否明确定义了 union 的任何使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58633465/