Posted Joe Chu cpp2 minutes read (About 363 words)0 visits
Avoid Naked Union
To ensure safety, encapsulate the union within a class or struct.
1. Naked Union
A naked union is not encapsulated within a class or struct.
nakedUnion.cpp
1 2 3 4 5
unionNakedUnion { int intValue; float floatValue; char charValue; };
Explanation of risks
Undefined behavior
Only one member of the union should be active at a time. Accessing an inactive member results in undefined behavior.
No type safety
A naked union does not track which member is currently active. If you accidentally access the wrong member, the program may produce incorrect results or crash.
2. Ecapsulation with class/struct
To mitigate the risk, we can wrap the union in a class or struct and use an enum to track the active member.