Move operation uses copy
Non-const
rvalue reference parameter of a function or operator is
copied instead of moved
Since R2021b
Description
Consider a callable entity that accepts a non-const
rvalue reference
(X&&
) parameter, called a consume parameter.
Polyspace® reports a defect if the callable entity copies the parameter instead of using
std::move()
. In particular, Polyspace reports a defect in each of these scenarios:
A move constructor or move assignment operator of a class copies data member or base class. This can happen if the move operator or move assignment operator omits calls to
std::move()
. For example, the move constructor of thewrapper
class copies the data memberdata
.Polyspace does not report a defect if move operations are unavailable for the copied data member or base class and if the data member is cheap to copy. Polyspace considers an object cheap to copy if the size of the object is less than twice the size of a pointer.class wrapper{ //... wrapper(wrapper&& input): data(input.data){ //Missing call to std::move() //... } private: std::string data; }
A consume parameter of a function is not completely moved by using
std::move()
in the function body. This can happen if the function body omits a call tostd::move()
or if the consume parameter is only partially moved. For example, in this code, the functionfunc()
accepts a vector as a consume parameter. In the body of the function,v
is copied instead of moved.As an exception, this defect is not reported if move constructors and move assignment operators move their arguments only partially.void func(vector<int> &&v) // func() consumes v { // comsume the vector process(v);// Defect- v is not consumed }
Risk
Consume parameters are intended to be moved using std::move()
.
Copying these objects results in inefficient code. Because the inefficient code compiles and
runs correctly, the omission of std::move()
can be difficult to
detect.
Fix
To fix this defect, use std::move()
to move consume parameters,
including arguments of move constructors or move assignment operators. When implementing
move semantics in a class, best practice is to use the default implicit move constructors
and move assignment operators by setting them as = default
. Instead of
managing raw resources, use containers from the Standard Template Library.
Performance improvements might vary based on the compiler, library implementation, and environment that you are using.
Examples
Result Information
Group: Performance |
Language: C++ |
Default: Off |
Command-Line Syntax:
MOVE_OPERATION_USES_COPY |
Impact: Medium |
Version History
Introduced in R2021bSee Also
Topics
- Interpret Bug Finder Results in Polyspace Desktop User Interface
- Interpret Bug Finder Results in Polyspace Access Web Interface (Polyspace Access)
- Address Results in Polyspace User Interface Through Bug Fixes or Justifications
- Address Results in Polyspace Access Through Bug Fixes or Justifications (Polyspace Access)