Show contents
Chapter 1 of 7 · 20 min
Move semantics
By the end of this chapter, you'll be able to
- Tell a copy constructor from a move constructor
- Explain what std::move does, and what it doesn't
- Apply the rule of zero, and the rule of five when it's needed
- Mark moves noexcept so that containers use them
Copy or move
A copy duplicates the data: the original stays intact. A move transfers the resources (allocated memory, for example) from one object to another: the original is left in a valid but unspecified state, which you should only destroy or reassign.
#include <iostream>
#include <utility>
#include <vector>
class Buffer {
public:
explicit Buffer(std::size_t size) : data_(size, 0) {
std::cout << "created (" << size << ")\n";
}
Buffer(const Buffer& other) : data_(other.data_) {
std::cout << "copy (" << data_.size() << ")\n";
}
Buffer(Buffer&& other) noexcept : data_(std::move(other.data_)) {
std::cout << "move\n";
}
std::size_t size() const { return data_.size(); }
private:
std::vector<int> data_;
};
int main() {
Buffer a(1000);
Buffer b = a; // copy: a stays usable
Buffer c = std::move(a); // move: c takes over a's data
std::cout << "a: " << a.size() << ", b: " << b.size() << ", c: " << c.size() << '\n';
std::vector<Buffer> v;
v.reserve(2);
v.push_back(std::move(b)); // moved into the vector
v.emplace_back(10); // built directly inside the vector
}
created (1000)
copy (1000)
move
a: 0, b: 1000, c: 1000
move
created (10)
Buffer(Buffer&& other)is the move constructor.Buffer&&is an rvalue reference: it binds to a temporary object, or to an object you've explicitly allowed to be "plundered".std::move(a)moves nothing: it's a simple cast that says "you may plundera". The real work is done by the move constructor selected thanks to this cast.- After the move,
ais empty here, because that's what the standard library's vector does. In general, a moved-from object is only guaranteed to be valid: don't rely on its content. emplace_back(10)builds the object directly inside the vector, with the given arguments: no copy and no move.
a no longer has data, but remains a valid object that can be destroyed or reassigned.
Text description of the animation
- a owns a block of memory of 1,000 integers.
- The copy allocates a second block and copies the 1,000 values: costly, but a is intact.
- The move copies nothing: c takes over the pointer to a's block. Only a few bytes change hands.
- a no longer has data, but remains a valid object that can be destroyed or reassigned.
The rule of zero, and the rule of five
A class that manages a resource itself (a new, an open file…) must define five special functions: destructor, copy constructor, copy assignment, move constructor, move assignment. That's the rule of five, and it's tedious and risky.
Good practice is the rule of zero: hand each resource to a member that knows how to manage it (std::vector, std::string, std::unique_ptr…) and write none of these five functions. The compiler then generates correct copies and moves, member by member. The Buffer class above only writes its own to show what happens; without the std::couts, you'd delete them.
Your turn
Worked exercise
Worked exercise: a class that follows the rule of zero
Write a Playlist class that holds a name (std::string) and a list of tracks (std::vector<std::string>), with an add(track) method and a size() method. Write no copy or move constructor. Then check that a copy is independent of the original, and that a move really transfers the tracks.
Hint 1
std::string and std::vector take care of copying and moving themselves.Hint 2
Show the solution and common mistakes
#include <iostream>
#include <string>
#include <utility>
#include <vector>
class Playlist {
public:
explicit Playlist(std::string name) : name_(std::move(name)) {}
void add(std::string track) { tracks_.push_back(std::move(track)); }
std::size_t size() const { return tracks_.size(); }
const std::string& name() const { return name_; }
private:
std::string name_;
std::vector<std::string> tracks_;
};
int main() {
Playlist party("Party");
party.add("Highlife");
party.add("Bossa nova");
Playlist copy = party; // member-by-member copy, generated by the compiler
copy.add("Kizomba");
std::cout << party.name() << ": " << party.size() << ", copy: " << copy.size() << '\n';
Playlist moved = std::move(copy);
std::cout << "moved: " << moved.size() << " tracks\n";
}
Party: 2, copy: 3
moved: 3 tracks
add(std::string track) takes its argument by value then moves it into the vector: with a temporary, no copy happens; with a variable, a single copy is made. It's a common idiom for parameters you store.
Common mistakes:
- Writing an empty destructor
~Playlist() {}"out of habit": its mere presence stops the compiler from generating the moves, and every move becomes a copy. - Using
copyafterstd::move(copy): its content is no longer guaranteed.
Summary
- 1A copy duplicates the data; a move transfers its ownership.
- 2std::move moves nothing: it allows the move, done by the right constructor.
- 3A moved-from object stays valid, but its content is unspecified.
- 4Rule of zero: hand resources to RAII members and write no special functions.
- 5Moves must be noexcept for containers to use them.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.