是否访问联合中的一个成员,该联合是从与另一个成员集未定义或未指定的联合复制而来的?

Is accessing one member in a union that copied from a union with another member set undefined or unspecified?

考虑以下代码片段,假设 AB 都是相同大小的普通类型,比如 int64_tdouble,或类似的东西:

union Punner {
  A x;
  B y;
};

Punner copy(Punner in)
{
  return in;
}

A pun(B in)
{
  Punner temp;
  temp.y = in;
  return copy(temp).x;
}

虽然我知道 temp.y = in 行开始了 tempy 成员的生命周期并且读取 temp.x 将是未定义的,但当我得到一个新副本时来自 copy 函数的 Punner 类型,是否应该假定副本的 y 成员的生命周期也已经开始,并且读取副本的 x 成员仍未定义,或者它只是未指定,在获得副本后,我实际上可以自由地从 xy 中读取(在这种情况下从 x 中读取)?

我知道我的问题在某些方面与 this 的问题相似,但遗憾的是我无法从对问题的回答中自信地确定我的问题的准确答案。

你应该想想内存中到底发生了什么。

Punner temp; //data in memory could be anything

temp.y = in; //data contains 8 bytes that describe an integer with the value in

copy(temp); //the copied data is 8 bytes that describe an integer with the value in

copy(temp).x; //accessing those 8 bytes as if they describe a double : getting giberish.