CodeBlanks Logo Icon CodeBlanks

Move vs copy

Learn the performance difference between move and copy semantics.

Move vs copy

A copy duplicates an object's resource; a move takes over the resource as is. Copying a large array is expensive; moving is cheap because only a pointer is transferred.

Since C++11 there are move constructors and std::move. std::move(a) does not actually move; it casts a to an rvalue so the move constructor is selected. After the move, the source object is valid but unspecified; usually it is nullptr.

Moving with std::move

std::move casts an lvalue to an rvalue. This makes the compiler select the move constructor. Example: std::string a = "Hello"; std::string b = std::move(a);. Here b takes over a's contents; a becomes empty.

After the move, a's state is unspecified but valid; its destructor runs safely. For large data (std::vector, std::string) move is much cheaper than copy; only three pointers/sizes are transferred, elements are not copied one by one.

Practice Move a std::string with std::move

In main define std::string a = "Hello";. Then write std::string b = std::move(a);. Finally write std::cout << b;.

Starter code

main.cpp
#include <iostream>
#include <string>

int main() {
    // Define a, move it to b with std::move and print
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <string>

int main() {
    std::string a = "Hello";
    std::string b = std::move(a);
    std::cout << b;
    return 0;
}

Expected output

Hello

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the move constructor parameter

Question
Buffer(Buffer&& ____) noexcept : data(other.data), size(other.size) { other.data = nullptr; }
Answer
Buffer(Buffer&& other) noexcept : data(other.data), size(other.size) { other.data = nullptr; }

Explanation: other is the name of the moved-from resource.

2 Match each tool to its role

Term Meaning
copy constructor Duplicates resource
move constructor Takes over resource
std::move Casts Lvalue to Rvalue
noexcept Exception guarantee

3 What does std::move do?

main.cpp
std::string b = std::move(a);
  • Casts Lvalue to Rvalue, move constructor is selected Correct answer
  • Creates a new copy
  • Deletes the object
  • Physically moves the resource

Explanation: std::move is only a cast; the actual move is done by the move constructor.

All lessons in Expert