Expensive use of
std::any_cast
An object is cast by-value using std::any_cast when casting
by-reference is more efficient
Since R2023b
Description
This defect is raised when both of these conditions are met:
You copy the output of
std::any_castwhere a reference can be used. Consider these situations:You initialize a
constreferencebby using a copy of the output ofstd::any_cast:It is unnecessary to copy the output ofconst T2& b = std::any_cast<T2>(a);
std::any_castto initializebbecause it is possible to initializebusing a reference.You invoke a
constmember function by using a copy of the output ofstd::any_cast:Creating a copy of the output is not necessary because it is possible to invoke thestd::any& a; //... std::any_cast<std::string>(a).empty();
constmember functionempty()by using a reference toa.
The output is expensive to copy. Nontrivial objects are typically expensive to copy. See
std::is_trivially_copyablein the C++ reference. Trivially copyable objects can also be expensive to copy if it is large.
Risk
Performing a by-value cast (std::any_cast<T>) is more expensive
than performing a by-reference cast (std::any_cast<const T&>) if
the parameter T is expensive to copy. In situations where copying the
parameter is unnecessary, the expensive copy makes your code inefficient. Polyspace® reports a defect on such inefficient code.
Fix
To fix this defect, cast objects by reference instead of by value. That is, replace this usage:
std::any_cast<T>(t)
std::any_cast<const T&>(t)
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_ANY_CAST |
| Impact: Medium |
Version History
Introduced in R2023b
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)
- Expensive-to-Read Objects in Bug Finder