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. 1

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 on any of these objects:

  • A const or const& object.

  • A temporary object. Temporary objects are not lvalues.

  • A pure rvalue such as a literal value.

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

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

#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 function foo() moves a literal value and a temporary local object. Polyspace reports violations on these move operations. Moving static class members is not a violation even if the member is accessed through a temporary instance of the class.

#include <utility>
class myClass {
public:
	myClass() = default;
	int localInt = 0;

	static int staticInt;
};

myClass::staticInt = 10;

myClass &get(void) ;

void foo(void) {
	// Moving literals
	auto var1 = std::move(42);  // Noncompliant
	// Moving temporary objects
	auto var2 = std::move(get().localInt);  // Noncompliant
	// Moving static class members
	auto var3 = std::move(get().staticInt);  // Compliant

}

Check Information

Group: Algorithms library
Category: Required

Version History

Introduced in R2024b

expand all


1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.

The MISRA coding standards referenced in the Polyspace Bug Finder™ documentation are from the following MISRA standards:

  • MISRA C:2004

  • MISRA C:2012

  • MISRA C:2023

  • MISRA C++:2008

  • MISRA C++:2023

MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.