Rule A5-2-1 (advisory, implementation, automated)

dynamic_cast should not be used.

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 289436 2017-10-04 10:45:23Z michal.szczepankiewicz $
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

JSF December 2005 [8]: AV Rule 178: Down casting (casting from base to derived class) shall only be allowed through one of the following mechanism: Virtual functions that act like dynamic casts (most likely useful in relatively simple cases); Use of the visitor (or similar) pattern (most likely useful in complicated cases). C++ Core Guidelines [11]: 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.