CWARN.MOVE.CONST

Constant value passed as argument to std::move()

The CWARN.MOVE.CONST checker detects and reports instances of calls to the std::move() method from the C++ Standard Template Libraries (STL) where the argument is const.

Vulnerability and risk

Calling std::move() on an object to cast it to an rvalue typically indicates that the programmer intends to perform move operations on it. However, move requests on a const object will be silently transformed into copy operations, as the const qualifier forbids modification of the object. Thus, when calling std::move() on a const object, the programmer may be expecting a move operation to be called, but the program will instead use a copy operation. This can potentially be much more expensive or cause hard to spot errors if there is code in the move operations that is expected to be called.

Code examples

Vulnerable code example 1

Copy
class X{
    /* custom copy and move constructors defined */
};
void foo(){
    const X bar;
    X quux = std::move(bar); //copy constructor is silently called here instead of expected move constructor
}

In the example above, Klocwork will report the expression 'std::move(bar)' as a CWARN.MOVE.CONST defect.

Fixed code example 1

Copy
class X{
    /* custom copy and move constructors defined */
};
void foo(){
    X bar;
    X quux{std::move(bar)};
}

Removing the const will allow the object to be moved as expected.

Fixed code example 2

Alternately, if the copy constructor is expected, then std::move() is superfluous and should be removed:

Copy
class X{
    /* custom copy and move constructors defined */
};
void foo(){
    const X bar;
    X quux{bar};
}