Main Content

Const return values may cause unnecessary data copies

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

Since R2020a

Description

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

The checker does not check if a move operation is possible for any calling function. The checker simply highlights const function return values that have class types with a nontrivial copy operation and a move operation.

Risk

The resources associated with the function return value are no longer required and can be moved to objects in the calling 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 return value, you explicitly prevent this compiler optimization.

In addition, the calling function can store the return value in a non-const object. The const-ness of the return value does not prevent any operation on the non-const object.

Fix

Remove const qualifiers from function return values.

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

Examples

expand all

#include <string>

class stringPair {
    std::string str1;
    std::string str2;
    
    public: 
    stringPair& operator=(const stringPair & aPair){
        if(&aPair != this) {
            str1 = aPair.str1;
            str2 = aPair.str2;
        }
        return *this;
    }
    
    const std::string getJoinedString(void) {
        return (str1 + str2);
    }
};

In this example, the const specifier on the return value of getJoinedString forces a copy operation instead of move operations.

Result Information

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

Version History

Introduced in R2020a