Main Content

AUTOSAR C++14 Rule A5-3-1

Evaluation of the operand to the typeid operator shall not contain side effects

Since R2020b

Description

Rule Definition

Evaluation of the operand to the typeid operator shall not contain side effects.

Rationale

The typeid operator evaluates its operand only if it is a call to a function that returns a reference to a polymorphic type (a polymorphic type is a class type that contains virtual functions). In all other cases, expressions provided to the typeid operator are not evaluated.

For code that is easier to maintain, avoid expressions with side effects altogether when using the typeid operator. You or another developer will be saved from tracking down the ingredients of the expression to their definitions and determining if the side effects actually occur.

Polyspace Implementation

The checker flags typeid operators with expressions that have side effects. Function calls are assumed to have side effects.

The checker message states whether the expression is evaluated or ignored. If the expression is evaluated and you want to retain the expression in the typeid operation instead of performing the evaluation in a separate statement, add comments to your result or code to avoid another review. See:

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

expand all

#include <iostream>
#include <typeinfo>

class Base
{
public:
    virtual ~Base();
};

class Derived: public Base
{
public:
    ~Derived();
};

Base& getObj();

void main()
{

    Base& b = getObj();

    std::cout << "Dynamic type:" << typeid(getObj()).name(); //Noncompliant
    std::cout << "Dynamic type:" << typeid(b).name(); //Compliant
}

The rule is violated when the typeid operand involves a function call.

Check Information

Group: Expressions
Category: Required, Non-automated

Version History

Introduced in R2020b