c++ - 在 C++ 的任何修订版中,是否明确定义了 union 的任何使用?

标签 c++ language-lawyer unions lvalue object-lifetime

考虑一个带有改变的“活跃成员”的简单 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 element X of S(E1), if modification of X would have undefined behavior under [basic.life], an object of the type of X 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/

相关文章:

c++ - 用其他语言编写的函数是否受关于 UB 的 C++ 规则的约束?

c - 只要您永远不取消引用它,持有未对齐的指针是否定义明确?

c++ - 'auto const' 和 'const auto' 是一样的吗?

c++ - 具有匿名结构的不同位映射

c++ - union 与 static_cast(void*)

c++ - 这里的const有什么用

c++ - 隐式转换产生 "error: taking address of temporary"(GCC vs clang)

c++ - 为什么 C++11 仍然强制可见性的词法排序

c++ - 在 map 中插入数组元素的时间复杂度是多少?

mysql - SQL 查询从一个表中获取除另一表中的特定记录之外的所有记录(按日期)