MISRA C++:2023 Rule 12.3.1
Description
Rule Definition
The union
keyword shall not be
used.
Rationale
It is undefined behavior to access a member of a union after
assigning a value to a different member of that union\ because each
assignment overwrites the memory location that is shared by all members.
In addition, if you access a member that has a nontrivial type such as
std::string
, it is your responsibility to manage
the lifetime of that member.
The rule does not apply to unions that you declare by using the
std::variant
feature introduced in C++17. This
feature throws an exception if you attempt to access a member using the
wrong type or a member that is not assigned, and automatically manages
the lifetimes of members of nontrivial types.
Polyspace Implementation
Polyspace® reports a declaration of a union as a violation.
Troubleshooting
If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.
Examples
Check Information
Group: Classes |
Category: Required |
Version History
Introduced in R2024b