Main Content

AUTOSAR C++14 Rule A5-2-1

dynamic_cast should not be used

Since R2020b

Description

Rule Definition

dynamic_cast should not be used.

Rationale

You use dynamic_cast to convert the type of a pointer or reference to a class along the inheritance hierarchy, for instance to convert a pointer to base class into a pointer to a derived class. The conversion incurs an overhead due to the type checking that is performed at run-time. This overhead is unsuitable for the low memory, speed, and predictable performance requirements of real-time systems.

If you cannot avoid dynamic casting in your application, consider using a custom implementation to perform the cast. You might also consider using virtual functions if you are casting to the most derived class, or static polymorphism with overloaded functions and templates. In the latter case, the types are resolved at compile-time which avoids the overhead.

Polyspace Implementation

Polyspace® flags all uses of dynamic_cast in your code.

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>


using namespace std;

class Base
{
public:
    virtual void f()
    {
        cout << "Using Base class\n";
    }
};

class Derived1 : public Base
{
public:
    virtual void f()
    {
        cout << "Using Derived class\n";
    }
};

class Derived2 : public Derived1
{
public:
    virtual void f()
    {
        cout << "Using Derived2 class\n";
    }
};


int main()
{
    Derived2* ptrd2 = new Derived2;

    Derived1* ptrd1 = dynamic_cast<Derived1*>(ptrd2); // Noncompliant
    ptrd1 -> f();

    Base* ptrb = dynamic_cast<Base*>(ptrd2); // Noncompliant
    ptrb -> f();
}

In this example, Base and Derived1 are indirect and direct base classes of Derived2 respectively. The use of dynamic_cast to upcast ptrd2 from type Derived2 to Derived1 then to Base is non-compliant. Note that in this case, the use of dynamic_cast is not necessary since an upcast can be performed through implicit conversion (Derived1 * ptr = ptrd2;).

Check Information

Group: Expressions
Category: Advisory, Automated

Version History

Introduced in R2020b