4 ms·
> Swapping through unions is UB Writing to union member and reading back as another member should be okay. But it does incur copy.
by flamedoge 8y ago
> Swapping through unions is UB
Writing to union member and reading back as another member should be okay. But it does incur copy.
- camgunz 8y agoReading from a union field other than the one last written to is explicitly UB. I wish this worked too, but it doesn't (compiler-specific guarantees aside).
- comex 8y agoIt's actually well-defined in the C standard (although the format of the byte representation is implementation-defined), but undefined behavior in the C++ standard: https://stackoverflow.com/a/11996970 https://stackoverflow.com/a/11996970 Since Linux is C, not C++, it should be fine; the author of the patch is just mistaken. (Note that in practice, this will work in C++ too, since most compilers support both C and C++ and don't change their optimization behavior based on which mode the code was compiled in; but of course there's no guarantee this won't change in the future.)
- camgunz 8y agoNot all compilers handle it like you'd expect, and it looks like that's because it's actually unspecified in the standard [1]. But furthermore, this will really only work for scalars. Plus you have to go and declare a whole new type to cast things safely. It's extremely awkward. [1]: https://blog.regehr.org/archives/959 https://blog.regehr.org/archives/959