Expensive dynamic_cast
Expensive dynamic_cast
is used instead of more efficient
static_cast
or const_cast
Since R2021b
Description
This defect is raised when dynamic_cast
is used on a pointer, which is
then immediately dereferenced. For
instance:
std::iostream* iostream_ptr; //... std::string str = dynamic_cast< std::stringstream* >( iostream_ptr )->str();
iostream
pointer iosreeam_ptr
is cast into a
stringstream
pointer, and then immediately dereferenced. Such use implies
that the casting always succeeds. When you know that a casting operation succeeds,
static_cast
or const_cast
are a more efficient
choice.Risk
When casting one class to another in a polymorphic hierarchy, you might want to use
dynamic_cast
when run-time type of the most derived class in the
hierarchy is unknown. The dynamic_cast
is more powerful because it checks
the type of the argument at run time and reports error if the check fails. These
functionalities make dynamic_cast
a more expensive operation than either
of static_cast
or const_cast
. Because
dynamic_cast
can achieve many different goals, its use might hide the
developers intent when casting. Using dynamic_cast
when cheaper or more
explicit casting operations might be more appropriate results in code that is inefficient
and more difficult to maintain. Because such code compiles and runs correctly, the
inefficiency might remain undetected.
Fix
To fix this defect, replace the dynamic_cast
with a more appropriate
cheaper option. For instance:
When calling virtual functions in a polymorphic base class, remove any casting operation.
When downcasting from a base class to derived class, use
static_cast
if the casting operation succeeds in all conditions.When sidecasting from one base class to another base class, use
static_cast
if the casting operation succeeds in all conditions.When upcasting from a derived class to a base class, use
static_cast
.To modify the
const
orvolatile
qualifiers of an object, useconst_cast
.Refactor your code to remove inappropriate casting such as casting between unrelated classes.
Performance improvements might vary based on the compiler, library implementation, and environment that you are using.
Examples
Result Information
Group: Performance |
Language: C++ |
Default: Off |
Command-Line Syntax:
EXPENSIVE_DYNAMIC_CAST |
Impact: Low |
Version History
Introduced in R2021b
See Also
Topics
- Interpret Bug Finder Results in Polyspace Desktop User Interface
- Interpret Bug Finder Results in Polyspace Access Web Interface (Polyspace Access)
- Address Results in Polyspace User Interface Through Bug Fixes or Justifications
- Address Results in Polyspace Access Through Bug Fixes or Justifications (Polyspace Access)