Move vs. Copy
In this lesson we'll see how the std::move utility proves more efficient than copying.
We'll cover the following
The function std::move
, defined in the header <utility>
, empowers the compiler to move its resource. In the so-called move semantic, the values from the source object are moved to the new object. Afterward, the source is in a well-defined but not specified state. Most of the times that is the default state of the source. By using std::move
, the compiler converts the source arg
to a rvalue reference: static_cast<std::remove_reference<decltype(arg)>::type&&> (arg)
.
The subtle difference is that if we create a new object based on an existing one, the copy semantic will copy the elements of the existing resource, whereas the move semantic will move the elements of the resource. So, of course, copying is expensive and moving is cheap. But there are additional serious consequences.
- With the copy semantic, it is possible that a std::bad_alloc will be thrown because our program is out of memory.
- The source of the move operation is in a “valid but unspecified state” afterward.
The second point can be explained well by std::string
example below.
If the compiler can not apply the move semantic, it falls back to the copy semantic.
Vector elements
Get hands-on with 1400+ tech skills courses.