简体   繁体   English

是否正在访问一个联合中的一个成员,该联合是从具有未定义或未指定的另一个成员集的联合复制的?

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

Consider the following code fragment, assuming that A and B are both trivial types of the same size, say int64_t and double , or something similar:考虑下面的代码片段,假设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;
}

While I know that the line temp.y = in starts the lifettime of the y member of temp and reading temp.x would be undefined, when I get a new copy of the Punner type from the copy function, should it be assumed that the copy's y member's lifetime is also already started, and reading the copy's x member still undefined, or is it simply unspecified, and after obtaining the copy, I may actually read from either the x or y freely (in this case reading from x )?虽然我知道,行temp.y = in开始中的lifettime y成员temp和阅读temp.x将是不确定的,当我得到的一个新副本Punner从类型copy功能,它应该被假定副本的y成员的生命周期也已经开始,读取副本的x成员仍未定义,或者只是未指定,在获得副本后,我实际上可以自由地从xy读取(在这种情况下从x读取)?

I know that my question is similar in some ways to this one, but regretfully I was not able to confidently determine a precise answer to my question from the responses to it.我知道我的问题在某些方面与这个问题相似,但遗憾的是,我无法从对它的回答中自信地确定我的问题的准确答案。

You should think about what is actually happening in the memory.您应该考虑内存中实际发生的事情。

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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM