AutosarC++17_03-A5.2.1ΒΆ

dynamic_cast should not be used

Required inputs: IR

Rationale

Implementations of dynamic_cast mechanism are unsuitable for use with real-time systems where low memory usage and determined performance are essential.

If dynamic casting is essential for your program, usage of its custom implementation should be considered. Also, usage of the dynamic_cast can be replaced with polymorphism, i.e. virtual functions.

Example
// $Id: A5-2-1.cpp 271715 2017-03-23 10:13:51Z piotr.tanski $
class A {
public:
virtual void f() noexcept;
};
class B : public A {
public:
void f() noexcept override {}
};
void fn(A *aptr) noexcept {
// ...
B *bptr = dynamic_cast<B *>(aptr); // Non-compliant

if (bptr != nullptr) {
// Use B class interface
} else {
// Use A class interface
}
}
See Also
  • C++ Core Guidelines [10]: C.146: Use dynamic_cast where class hierarchy navigation is unavoidable.
  • Journal of Computing Science and Engineering, Damian Dechev, Rabi Mahapatra, Bjarne Stroustrup: Practical and Verifiable C++ Dynamic Cast for Hard Real-Time Systems.
  • Software-Practice and Experience, Michael Gibbs and Bjarne Stroustrup: Fast dynamic casting.

Possible Messages

Key

Text

Severity

Disabled

dynamic_cast

dynamic_cast should not be used.

None

False

Options