TICS Coding Standard Viewer 
TIOBE Software Quality Framework
Print-friendly version
©TIOBE Software www.tiobe.com
C++ Coding Standard

Rule:  PCA#010Checked automatically with code checker

Synopsis:Do not use unions
Severity Level:6
Category:Parts of C++ to Avoid


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 SuperFloat;

See the reference to StackOverflow for a discussion when to use variants over unions.

Literature References: