Local variable is created by copy from a const reference and not
modified later
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 *).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.
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.
| Group: Performance |
| Language: C++ |
| Default: Off |
Command-Line Syntax:
EXPENSIVE_LOCAL_VARIABLE |
| Impact: Medium |
Expensive copy in a range-based for
loop iteration | Expensive pass by value | Expensive return by
value | Unmodified variable not
const-qualified