C++ Move Semantics
Copying a std::string with a million characters means allocating new memory and copying a million bytes. But often the original is about to be thrown away anyway — a temporary returned from a function, or a local variable you will never use again. Move semantics (C++11) let an object steal the resources of such an object instead of copying them. For a string or vector, a move just copies a pointer and a size, then leaves the source empty.
Lvalues and rvalues
To decide between copying and moving, C++ distinguishes two kinds of expressions:
| Kind | Description | Examples |
|---|---|---|
| lvalue | has a name / identity; you can take its address | x, v[0], *ptr |
| rvalue | a temporary, about to disappear | 42, a + b, makeString() |
An rvalue reference, written T&&, binds only to rvalues. Overloading on const T& vs T&& lets a function tell whether it may steal from its argument:
#include <iostream>
#include <string>
using namespace std;
void take(const string& s) { cout << "lvalue: copy \"" << s << "\"\n"; }
void take(string&& s) { cout << "rvalue: may steal \"" << s << "\"\n"; }
int main() {
string name = "Ada";
take(name); // name is an lvalue
take(name + " Lovelace"); // temporary -> rvalue
take(string("temp")); // temporary -> rvalue
take(std::move(name)); // explicitly treated as an rvalue
}lvalue: copy "Ada"
rvalue: may steal "Ada Lovelace"
rvalue: may steal "temp"
rvalue: may steal "Ada"
std::move
std::move does not move anything by itself — it is just a cast that says "treat this lvalue as an rvalue; I won't need its value any more". The actual moving happens in the move constructor or move assignment of the target:
#include <iostream>
#include <string>
#include <vector>
#include <utility>
using namespace std;
int main() {
string a = "a fairly long string that lives on the heap";
string b = std::move(a); // b steals a's buffer
cout << "b: " << b << "\n";
cout << "a is now empty? " << boolalpha << a.empty() << "\n";
vector<int> big(1'000'000, 7);
vector<int> other = std::move(big); // no million-element copy
cout << other.size() << " " << big.size() << "\n";
}b: a fairly long string that lives on the heap
a is now empty? true
1000000 0
Warning: After
std::move(x),xis in a "valid but unspecified" state. For standard types you may assign a new value to it or destroy it, but don't rely on its contents.
Writing a move constructor
Classes that manage a resource directly need a move constructor and move assignment operator. They take the other object's resource and leave it in an empty, safe-to-destroy state. Mark them noexcept so containers can use them when reallocating:
#include <iostream>
#include <utility>
using namespace std;
class Buffer {
public:
explicit Buffer(size_t n) : size_(n), data_(new int[n]{}) {
cout << "allocate " << n << "\n";
}
~Buffer() {
if (data_) cout << "free " << size_ << "\n";
delete[] data_;
}
Buffer(const Buffer& other) : size_(other.size_), data_(new int[other.size_]) {
for (size_t i = 0; i < size_; i++) data_[i] = other.data_[i];
cout << "copy " << size_ << "\n";
}
Buffer(Buffer&& other) noexcept
: size_(std::exchange(other.size_, 0)), data_(std::exchange(other.data_, nullptr)) {
cout << "move " << size_ << "\n";
}
Buffer& operator=(Buffer other) noexcept { // copy-and-swap: handles both copy and move
swap(size_, other.size_);
swap(data_, other.data_);
return *this;
}
size_t size() const { return size_; }
private:
size_t size_;
int* data_;
};
int main() {
Buffer a(3);
Buffer b = a; // copy constructor
Buffer c = std::move(a); // move constructor: no allocation
cout << "a.size() = " << a.size() << ", c.size() = " << c.size() << "\n";
}allocate 3
copy 3
move 3
a.size() = 0, c.size() = 3
free 3
free 3
Only two buffers were ever allocated, and each is freed exactly once. The moved-from a holds nullptr, so its destructor frees nothing.
The rule of zero (and five)
If your class manages a raw resource, you typically need all five special members: destructor, copy constructor, copy assignment, move constructor and move assignment — the rule of five. Much better is the rule of zero: build your class out of members that already manage themselves (string, vector, unique_ptr). Then the compiler-generated copy and move operations are correct automatically:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct Playlist { // rule of zero: no special members written
string title;
vector<string> songs;
};
int main() {
Playlist p{"Road trip", {"Song A", "Song B", "Song C"}};
Playlist moved = std::move(p); // compiler-generated move
cout << moved.title << " has " << moved.songs.size() << " songs\n";
cout << "original now has " << p.songs.size() << " songs\n";
vector<Playlist> library;
library.push_back(std::move(moved)); // moved into the vector, not copied
cout << library[0].songs[1] << "\n";
}Road trip has 3 songs
original now has 0 songs
Song B
Where moves happen automatically
- Returning a local variable from a function (often the copy is elided entirely).
- Passing a temporary:
v.push_back(string("x")). - Standard containers moving their elements when they grow (if the move constructor is
noexcept).
Tip: Don't write
return std::move(local);— it can prevent the compiler from eliding the copy entirely. Justreturn local;.
Test yourself
What does std::move(x) actually do?
- Copies x to a new location
- Casts x to an rvalue so it may be moved from
- Deletes x
- Moves x to the heap
Which of these is an rvalue?
- A named variable
x v[0]- The result of
a + b *ptr
What is the "rule of zero"?
- Never use pointers
- Design classes so they need no user-written copy/move/destructor
- Initialise all members to zero
- Use zero-based indexing