Moving an object in C++ means transferring the resources that it owns to another object and leaving the source in a valid but unspecified state. A move is not a copy. It is what lets a buffer, a string or a file handle change hands without duplicating the underlying data. Since C++11 the compiler uses moves automatically in most of the situations where it previously copied, which is why modern C++ can return large objects by value without a performance penalty.
The previous lesson in this module covered "What Is the Rule of Zero and the Rule of Five?", and the next lesson in this module is about "Which Operators Can You Overload and How?".
What std::move actually does
std::move does not move anything. It is a cast that converts an lvalue into an rvalue, and that is the signal that triggers the move constructor or the move assignment operator.
#include <iostream>
#include <string>
#include <utility>
class Buffer {
public:
explicit Buffer(const std::string& label)
: data_(new int[4]{1, 2, 3, 4}), label_(label) {
std::cout << "constructed " << label_ << '\n';
}
Buffer(const Buffer& other)
: data_(new int[4]), label_(other.label_ + " (copy)") {
std::cout << "copy constructed " << label_ << '\n';
}
Buffer(Buffer&& other) noexcept
: data_(other.data_), label_(other.label_ + " (moved)") {
other.data_ = nullptr;
std::cout << "move constructed " << label_ << '\n';
}
~Buffer() {
delete[] data_;
std::cout << "destroyed " << label_ << '\n';
}
int* data_;
private:
std::string label_;
};
int main() {
Buffer source("source");
Buffer destination = std::move(source);
std::cout << "destination data: " << destination.data_[0] << '\n';
return 0;
}The output shows that a move happened rather than a copy.
constructed source
move constructed source (moved)
destination data: 1
destroyed source (moved)
destroyed sourceNotice that the buffer was not duplicated. The pointer was transferred and the source was left with a null pointer, so its destructor does nothing.
The moved-from state
A moved-from object is in a valid but unspecified state. Valid means that you may still call its destructor, assign to it, or move from it again. Unspecified means that you may not rely on what it contains. It might be empty, it might hold the old value, and the exact behaviour is up to the type.
#include <iostream>
#include <string>
int main() {
std::string first = "a long piece of text";
std::string second = std::move(first);
std::cout << "second: " << second << '\n';
std::cout << "first is empty?: " << first.empty() << '\n';
// The moved-from string is still usable: assigning to it works.
first = "reused";
std::cout << "after reuse: " << first << '\n';
return 0;
}The output shows the typical behaviour of the standard library, where a moved-from string is left empty.
second: a long piece of text
first is empty?: 1
after reuse: reusedAnd the rule is simple. Treat a moved-from object as a fresh object that you may assign to, and never read its contents expecting anything in particular.
Move assignment
Move assignment is the same idea applied to an object that already exists. The old resource is released and the new one is taken over.
#include <iostream>
#include <string>
#include <utility>
class Buffer {
public:
explicit Buffer(const std::string& label)
: data_(new int[4]{1, 2, 3, 4}), label_(label) {}
Buffer& operator=(Buffer&& other) noexcept {
if (this != &other) {
delete[] data_; // release what we had
label_ = std::move(other.label_);
data_ = other.data_; // take over what they had
other.data_ = nullptr;
}
return *this;
}
~Buffer() { delete[] data_; }
int* data_;
private:
std::string label_;
};
int main() {
Buffer source("source");
Buffer destination("destination");
destination = std::move(source);
std::cout << "destination data: " << destination.data_[0] << '\n';
return 0;
}The output shows the destination now holding the buffer.
destination data: 1The noexcept requirement
A move constructor and a move assignment operator should be marked noexcept. The reason is that std::vector reallocates its storage by moving the elements, and if a move can throw then the vector has to fall back to copying to preserve the contents.
#include <iostream>
#include <string>
#include <utility>
#include <vector>
class Buffer {
public:
Buffer() : data_(new int[4]{1, 2, 3, 4}) {}
Buffer(Buffer&& other) noexcept
: data_(other.data_) {
other.data_ = nullptr;
}
Buffer& operator=(Buffer&& other) noexcept {
if (this != &other) {
delete[] data_;
data_ = other.data_;
other.data_ = nullptr;
}
return *this;
}
Buffer(const Buffer& other) : data_(new int[4]) {
for (int i = 0; i < 4; ++i) {
data_[i] = other.data_[i];
}
}
~Buffer() { delete[] data_; }
int* data_;
private:
int size_ = 0;
};
int main() {
std::vector<Buffer> fleet;
for (int i = 0; i < 4; ++i) {
fleet.emplace_back();
}
std::cout << "buffers: " << fleet.size() << '\n';
std::cout << "first value: " << fleet[0].data_[0] << '\n';
return 0;
}Marking the move noexcept lets the vector move the elements into the new storage instead of copying them, which is both faster and the only way that the buffer pointers stay unique.
Moving on return
Returning a local variable by value was expensive in the old C++, because the return value had to be copied out of the function. Since C++11 the copy is elided, and in C++17 returning a named local is guaranteed to be moved.
#include <iostream>
#include <string>
class Buffer {
public:
Buffer() : data_(new int[4]{7, 8, 9, 10}) {}
Buffer(const Buffer& other) : data_(new int[4]) {
for (int i = 0; i < 4; ++i) {
data_[i] = other.data_[i];
}
}
Buffer(Buffer&& other) noexcept : data_(other.data_) {
other.data_ = nullptr;
}
~Buffer() { delete[] data_; }
int first() const { return data_[0]; }
private:
int* data_;
};
Buffer make_buffer() {
Buffer local;
return local; // moved out, not copied
}
int main() {
Buffer buffer = make_buffer();
std::cout << "first: " << buffer.first() << '\n';
return 0;
}The output shows that the value survived the move.
first: 7And returning a large object by value is now perfectly reasonable. Writing std::move on the returned value would actually make things worse, because it prevents the elision.
Quick reference
std::moveis a cast to an rvalue, and the move constructor or the move assignment does the work.- A move transfers the ownership instead of duplicating the data.
- A moved-from object is valid but unspecified. Assign to it, and do not read it.
- Mark the move operations
noexceptso that the containers can move instead of copying. - Returning a local variable is moved, and usually elided, in modern C++.
- Do not write
std::moveon a return value.
Try it yourself: write a class that owns a buffer and prints a message in its copy constructor, its move constructor and its destructor. Copy one object and move another, and compare the messages. Then put the class in a std::vector that grows, and check whether the elements are copied or moved when the vector reallocates. Finally, remove noexcept from the move and watch the behaviour change.