Expensive local variable copy
Local variable is created by copy from a const reference and not
modified later
Since R2021a
Description
This defect occurs when a local variable is created by copy from a
const reference but not modified later.
For instance, the variable name is created by copy from a
const reference returned from the get_name
function:
const std::string& get_name();
...
void func {
std::string name = get_name();
}2 * sizeof(void *).Risk
If a variable is created from a const reference and not modified
later, the variable itself can be defined as a const reference. Creating
a const reference avoids a potentially expensive copy operation.
Fix
Avoid creating a new local variable by copy from a const reference if
you do not intend to modify the variable later. Create a const reference
instead.
For instance, in the preceding section, you can redefine the variable
name
as:
const std::string& get_name();
...
void func {
const std::string& name = get_name();
}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_LOCAL_VARIABLE |
| Impact: Medium |
Version History
Introduced in R2021a
See Also
Find defects
(-checkers) | Expensive pass by value | Expensive return by
value | Expensive copy in a range-based for
loop iteration | Unmodified variable not
const-qualified
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