Main Content

Const parameter values may cause unnecessary data copies

Const parameter values may prevent a move operation resulting in a more performance-intensive copy operation

Since R2020a

Description

This defect occurs when const objects as function parameters may prevent a move operation resulting in a more performance-intensive copy operation.

The checker does not check if a move operation is possible in a given function call. The checker simply highlights const function parameters that have class types with a nontrivial copy operation and a move operation. You can determine for yourself if the parameter can be moved to the called function.

Risk

If the function argument is an rvalue, the resources associated with the argument are no longer required and can be moved to parameters in the called function. Compilers ensure that the move operation is used in this situation since they are generally less expensive than copy operations. If you use a const object as function parameter, you explicitly prevent this compiler optimization.

Fix

If you think that the parameter can be moved to the called function, remove the const qualifier from the flagged function parameter.

Performance improvements might vary based on the compiler, library implementation, and environment that you are using.

Examples

expand all

#include <string>

std::string getStringFromUser() {
    //Get a string of arbitrary length
}

void countWordsInString(const std::string str) {
    //Count number of words in string
}

void main() {
    std::string aString = getStringFromUser();
    std::string anotherString = getStringFromUser();
    
    std::string joinedString = aString + anotherString;
    
    countWordsInString(joinedString);
    countWordsInString(aString + anotherString);
}

In this example, the checker flags the const str::string parameter str. In situations where a move operation is possible, for example in the call:

countWordsInString(aString + anotherString);
the const parameter forces a copy operation, which can be significantly more expensive.

Result Information

Group: Performance
Language: C++
Default: Off
Command-Line Syntax: CONST_PARAMETER_VALUE
Impact: Low

Version History

Introduced in R2020a