AutosarC++18_10-A5.2.1ΒΆ
dynamic_cast should not be used
Required inputs: IR
| Level | advisory |
|---|---|
| Target | implementation |
| Enforcement | automated |
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.
Possible Messages
Key |
Text |
Severity |
Disabled |
|---|---|---|---|
dynamic_cast |
dynamic_cast should not be used. |
None |
False |
Options
This rule shares the following common options: confidence, exclude_in_macros, exclude_messages_in_system_headers, excludes, extend_exclude_to_macro_invocations, includes, justification_checker, languages, post_processing, provider, report_at, severity
The following places define options that affect this rule: Stylechecks, Analysis-GlobalOptions
This rule has no individual options.