This rule is part of MISRA C++:2023.
Usage of this content is governed by Sonar’s terms and conditions. Redistribution is
prohibited.
Rule 8.2.9 - The operand to typeid shall not be an expression of polymorphic class type
[expr.typeid]
Category: Required
Analysis: Decidable,Single Translation Unit
Amplification
This rule does not apply to typeid( //type-id// ).
std::type_info const & type { typeid( std::iostream ) }; // Rule does not apply
Rationale
An expression of polymorphic class type used as the operand to typeid may or may not be evaluated at runtime. It is
therefore unclear if potential side effects within the expression will or will not occur.
Additionally, typeid could throw a std::bad_typeid exception, but this will only happen if the operand has polymorphic
class type.
Note: this rule applies even when there is no runtime evaluation.
Example
#include <typeinfo>
struct S { }; // Non-polymorphic
struct P { virtual void foo() {} }; // Polymorphic
const std::type_info & foo( S * s )
{
return typeid( *s ); // Compliant
}
const std::type_info & foo( P * p )
{
return typeid( *p ); // Non-compliant
}
const std::type_info & foo( P p )
{
return typeid( p ); // Non-compliant
}
const std::type_info & bar( P * p )
{
return typeid( p->foo() ); // Compliant - type is always 'void'
}
Copyright The MISRA Consortium Limited © 2023