AUTOSAR C++14 Rule A18-9-3
Description
Rule Definition
The std::move shall not be used on objects declared const or const&.
Rationale
When you use std::move()
on an object, it is cast into an rvalue. The
compiler then manages the resources in the object by calling the constructor or operator
with the closest matching parameter list. If you call std::move()
on a
const
or const&
type object, the call returns a
const
or const&
type rvalue. Because move
constructors and operators do not take a const
type argument, the
compiler calls the copy constructor or operator instead of the move constructor or operator.
Consider this code snippet where a const
object is copied when you might
expect a move after a call to
std::move()
.
class string{ //... public: string(const string& rhs);// copy contructor string(string&& rhs); //move constructor }; void print(string text) { cout<<text; //... } int main(){ int const message = "Error"; //.. print(std::move(message))// the copy constructor is called }
std::move(message)
is the rvalue const
string&&
. Between the move and copy constructors of class
string
, only the copy constructor accepts const
type
argument. The compiler calls the copy constructor and copies the resources of
message
into text
.Because std::move()
does not move a const
or
const&
type object, avoid using std::move()
on
const
or const&
objects. If you intend to move
resources from an object, do not declare it as const
or
const&
.
Polyspace Implementation
Polyspace® flags use of std::move()
on:
Objects that are declared
const
orconst&
.Objects that are cast to
const
orconst&
.
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
Check Information
Group: Language support library |
Category: Required, Automated |
Version History
Introduced in R2020a