On 12/11/2015 4:54 PM, Ion Gaztañaga wrote:
Reading from an inactive member of a union is plain and simply undefined behavior. To read and write the bits of the `float` in a well defined way use `std::memcpy`.
Curiously, it is undefined in C++, whereas well-defined in C:
"6.5.2.3 Structure and union members
If the member used to read the contents of a union object is not the same as the member last used to store a value in the object, the appropriate part of the object representation of the value is reinterpreted as an object representation in the new type as described in 6.2.6 (a process sometimes called ‘‘type punning’’). This might be a trap representation."
Since C++ includes C as a normative reference it would be a good idea to allow it also in C++. memcpy is fine if the compiler optimizes it as an intrinsic, but inefficient in some implementations to copy only a couple of bytes.
C has *vastly* weaker aliasing rules than C++ (to the point that several C implementations choose to follow the C++ rules instead). For more details see the thread at http://lists.boost.org/Archives/boost/2015/11/226663.php If your implementation of choice gives you poor codegen for `memcpy` then I'll suggest you file a bug against it. We would all benefit from that. Regards, -- Agustín K-ballo Bergé.- http://talesofcpp.fusionfenix.com