Main Content

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();
}
The defect is raised only if the local variable has a non-trivially copyable type or a trivially copyable type with size greater than 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

expand all

#include <string>

class Task
{
public:
    // ...
    const std::string& get_name() const;
    // ...
private:
    // ...
};

void inspect( const Task& task )
{
    // ...
    const std::string name = task.get_name(); 
    // ...
}

In this example, the variable name is created by copy from a const reference but not modified later.

Correction – Use const Reference

To avoid a potentially expensive copy operation, avoid creating a new local variable if you do not intend to modify the variable later. Instead, assign the const-reference return value to another const reference.

#include <string>

class Task
{
public:
    // ...
    const std::string& get_name() const;
    // ...
private:
    // ...
};

void inspect( const Task& task )
{
    // ...
    const std::string& name = task.get_name(); 
    // ...
}

Result Information

Group: Performance
Language: C++
Default: Off
Command-Line Syntax: EXPENSIVE_LOCAL_VARIABLE
Impact: Medium

Version History

Introduced in R2021a