Main Content

Const std::move input may cause a more expensive object copy

Const std::move input cannot be moved and results in more expensive copy operation

Since R2020b

Description

This defect occurs when you use std::move on a const object, resulting in a more expensive copy operation.

The checker raises a violation only for class types with a nontrivial copy operation and a move operation.

Risk

A const object cannot be modified and therefore cannot be moved. An std::move on a const object silently falls back to a copy operation without compilation errors. Your code might suffer from poorer performance without you noticing the issue.

Fix

Remove the const qualifier from the object being moved.

If you want a copy operation instead, remove the redundant std::move call.

Note that this issue also triggers the checker Move operation on const object, which applies to all move operations on const objects irrespective of whether the class type has a move operation and a nontrivial copy operation. If you decide to justify the issue, you can use the same justification for both results.

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

Examples

expand all

#include <string>

#include <string>

class MyClass {
public:
    void setName( const std::string& name ) {
        m_name = std::move( name );
    }
private:
    std::string m_name;
};

In this example, std::move is called on a const objects, name. Instead of a move assignment, a possibly more expensive copy assignment takes place.

Remove const Qualifiers

If you want move operations, remove the const qualifier from the definitions of the objects being moved.

#include <string>

#include <string>

class MyClass {
public:
    void setName( std::string& name ) {
        m_name = std::move ( name );
    }
private:
    std::string m_name;
};

Result Information

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

Version History

Introduced in R2020b