Main Content

MISRA C++:2023 Rule 28.6.1

The argument to std::move shall be a non-const lvalue

Since R2024b

Description

Rule Definition

The argument to std::move shall be a non-const lvalue.

Rationale

When arguments to std::move() are specified as const or const&, the copy constructor is called instead of the move constructor.

Avoid calling the std::move() function on const objects. If you want to perform a move operation, cast the const object to a non-const object, and then move the non-const object.

Polyspace Implementation

Polyspace® reports a violation of this rule when the std::move() function is called with an object declared const or const&.

Troubleshooting

If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

#include <utility> 
#include <vector>

int main() {
    const std::vector<int> vec1 = {1, 2, 3, 4, 5};

    std::vector<int> vec2 = std::move(vec1);	//Noncompliant
}

In this example, the code attempts to use std::move() on vec2. Because vec2 is a const lvalue, this operation is noncompliant.

Check Information

Group: Algorithms library
Category: Required

Version History

Introduced in R2024b