MISRA C++:2023 Rule 8.2.9
The operand to typeid
shall not be an expression of polymorphic
class
type
Since R2024b
Description
Rule Definition
The operand to typeid
shall not be an expression of
polymorphic class
type.
Rationale
Using expressions of polymorphic class types as operands to typeid
operator can lead to unpredictable run time behavior or exception:
Whether the compiler evaluates the expression at run time is uncertain. If the expressions have side effect, then the behavior of the code at run time can become unpredictable.
Evaluating the expression can lead to dereferencing of
nullptr
and an exception ofstd::bad_typeid
This rule applies even if your code performs no runtime evaluation of the
typeid
operands. The rule does not apply if you do not use
expressions of a polymorphic class type as operands to typeid
(
type-id
):
std::type_info const& type(typeid(std::iostream)); // Rule does not apply
std::iostream
is not an instance of a polymorphic class. Because
the operand of typeid
is not an expression of polymorphic class
types, such use of the typeid
operator is not a violation of this
rule.Polyspace Implementation
Polyspace® reports a violation of this rule if you use an expression of polymorphic
class type as the operand to the typeid
operator. A polymorphic class
is a class that contains or inherits at-least one virtual
function.
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: Expressions |
Category: Required |
Version History
Introduced in R2024b