繁体   English   中英

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

[英]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开始中的lifettime y成员temp和阅读temp.x将是不确定的,当我得到的一个新副本Punner从类型copy功能,它应该被假定副本的y成员的生命周期也已经开始,读取副本的x成员仍未定义,或者只是未指定,在获得副本后,我实际上可以自由地从xy读取(在这种情况下从x读取)?

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

您应该考虑内存中实际发生的事情。

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