Why is this an issue?
This is a draft version of a MISRA C++ 202x rule proposed for public review.
MISRA Rule 9.3.1
Category: Required
Analysis Type: Decidable,Single Translation Unit
Rationale
A member of a union can be written and the same member can then be read back in a well-defined manner.
However, writing to one union member and then reading back from a different union member results in undefined behaviour. In addition, the
use of a member of non-trivial type requires manual control of its lifetime. For these reasons, unions shall not be used.
The class std::variant
, available since C++17, provides a type-safe union that can be used to store a value of one type from a fixed
set of alternatives. In contrast to unions, the alternatives are accessed by type (if the types are different) or index, not by name. It is impossible
to access an inactive member of a std::variant
. For example, trying to access an inactive member via std::get()
will lead to
an exception being thrown.
Example
union Data1 // Non-compliant
{
int32_t i;
float j;
};
using Data2 = std::variant< int32_t, float >; // Rule does not apply
Copyright The MISRA Consortium Limited © 2023
Resources
Related rules
S6147 targets the same defect as this rule but for a non-mission-critical context.