On 2015-12-01 18:32, Agustín K-ballo Bergé wrote:
On 12/1/2015 11:59 AM, Andrey Semashev wrote:
It's not just syntax. If I'm not mistaken, the union-based type punning has advantage over memcpy - it allows the code to be constexpr.
No, it doesn't. There's no undefined behavior allowed in a constant expression. Furthermore, the rules for `union` member access are stronger for constant expressions, there's no common initial sequence rule nor anything like it since constant expressions do not work under the memory object model. Even compilers with implementation-specific behavior would reject it.
I see. I tried this locally with gcc and it succeeded, but apparently I used bitwise_cast in a context that allowed runtime execution, although the compiled code was still using a constant. In a purely constant expression it indeed fails to compile. Good to know.
After all, it would have to be an implementation specific choice, if we don't know whether `memcpy` will be optimized then we can't assume that the undefined behavior will do the `memcpy` you expect.
That's true, although I can't remember any particular compiler implementing a different behavior wrt unions.