Synopsis: | Do not use unions |
Language: | C++ |
Severity Level: | 6 |
Category: | Parts of C++ to Avoid |
Description: |
One way to simulate unions is using variants. Variants are type-safe unions. They are available since C++17. An instance of std::variant at any given time either holds a value of one of its alternative types, or in the case of error - no value. The latter state is hard to achieve. Example (wrong): union SuperFloat { float f; int i; }; Example (right): using std::variant See the reference to StackOverflow for a discussion when to use variants over unions. |
Literature References: |
StackOverflow |