MISRA C++:2023 Rule 12.3.1
Description
Rule Definition
The union
keyword shall not be
used. 1
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
1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.
The MISRA coding standards referenced in the Polyspace Bug Finder™ documentation are from the following MISRA standards:
MISRA C:2004
MISRA C:2012
MISRA C:2023
MISRA C++:2008
MISRA C++:2023
MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.