[英]Is accessing one member in a union that copied from a union with another member set undefined or unspecified?
考虑下面的代码片段,假设A
和B
都是相同大小的平凡类型,比如int64_t
和double
,或类似的东西:
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
成员仍未定义,或者只是未指定,在获得副本后,我实际上可以自由地从x
或y
读取(在这种情况下从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.