diff options
author | Wladimir J. van der Laan <laanwj@protonmail.com> | 2020-02-26 19:00:18 +0100 |
---|---|---|
committer | Wladimir J. van der Laan <laanwj@protonmail.com> | 2020-02-26 19:00:24 +0100 |
commit | e5d47ed8fd3724cc5295fca70573f1edf552ff62 (patch) | |
tree | 92296f18fe5766efab9cdb26704fc3589d58809c /test | |
parent | 89a97a71f2eeb5cd99cd77f31cdc64e194f16ab6 (diff) | |
parent | 0653939ac130eddffe40c53ac418bea305d3bf82 (diff) |
Merge #18167: Fix a violation of C++ standard rules where unions are used for type-punning
0653939ac130eddffe40c53ac418bea305d3bf82 Add static_asserts to ser_X_to_Y() methods (Samer Afach)
be94096dfb0c4862e2314cbae4120d7360b08ef2 Fix a violation of C++ standard rules that unions cannot be switched. (Samer Afach)
Pull request description:
Type punning in C++ is not like C. As per the C++ standard, one cannot use unions to convert the bit type. A discussion about this can be found [here](https://stackoverflow.com/questions/25664848/unions-and-type-punning). In C++, a union is supposed to only hold one type at a time. It's intended to be used only as `std::variant`. Switching types is undefined behavior.
In fact, C++20 has a special casting function, called [`bit_cast`](https://en.cppreference.com/w/cpp/numeric/bit_cast) that solved this problem.
Why has it been working so far? Because some compilers tolerate using unions and switching types, like gcc. More information [here](https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html#Type-punning).
One important thing to mention is that performance is generally not affected by that memcpy. Compilers are smart enough to convert that to a memory cast when possible. But we have to do it the right way, otherwise, it's jut undefined behavior that depends on the compiler.
ACKs for top commit:
practicalswift:
ACK 0653939ac130eddffe40c53ac418bea305d3bf82
elichai:
ACK 0653939ac130eddffe40c53ac418bea305d3bf82
laanwj:
Code review ACK 0653939ac130eddffe40c53ac418bea305d3bf82
kristapsk:
ACK 0653939ac130eddffe40c53ac418bea305d3bf82
Tree-SHA512: f6e89de39fc964750429139bab6b5a1346f7060334b7afa020e315bdad8f8c195bce2b8a9e343f06e7fff175e2dfb1cdabfcb6fe405bea0febe4962f0cc62557
Diffstat (limited to 'test')
0 files changed, 0 insertions, 0 deletions