Search code examples
c++c++11type-punning

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:

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)?

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.


Solution

  • 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.