Transfer a resource instead of duplicating it, and let the compiler know when duplication is unnecessary.
The Analogy: Handing Over the Suitcase
Suppose a friend needs your packed suitcase. There are two ways to give it to them.
The first is to buy an identical empty case, unpack yours item by item into theirs, and then keep your own. Both of you end up with a full suitcase. This is a copy: correct, sometimes exactly what you want, and expensive in proportion to how much is inside.
The second is to hand them the handle and walk away. Nothing is unpacked, nothing is bought, and the transfer takes the same amount of time whether the case holds one shirt or forty. You are left holding nothing — which is fine, as long as you do not then try to wear a shirt out of it. This is a move.
Before C++11, the language had only the first option for user-defined types. Returning a large std::vector from a function, or growing one by push_back, meant real duplication. Move semantics added the second option, and the compiler now takes it automatically whenever the source is something nobody will look at again — a temporary, a returned value, an object you have explicitly said you are finished with.
Syntax or Core Structure
A type opts in by declaring a move constructor and a move assignment operator, both taking T&&. Here every operation announces itself, so you can watch which one the compiler picks:
#include <iostream>
#include <string>
#include <vector>
#include <utility>
struct Message {
std::string text;
Message(std::string t) : text(std::move(t)) {
std::cout << " ctor " << text << "\n";
}
Message(const Message& other) : text(other.text) {
std::cout << " COPY " << text << "\n";
}
Message(Message&& other) noexcept : text(std::move(other.text)) {
std::cout << " move " << text << "\n";
}
Message& operator=(const Message& other) {
text = other.text;
std::cout << " COPY= " << text << "\n";
return *this;
}
Message& operator=(Message&& other) noexcept {
text = std::move(other.text);
std::cout << " move= " << text << "\n";
return *this;
}
};
Message make(std::string t) { return Message(std::move(t)); }
int main() {
std::cout << "1. construct:\n";
Message a("alpha");
std::cout << "2. copy from an lvalue:\n";
Message b = a;
std::cout << "3. move from an lvalue, made explicit:\n";
Message c = std::move(a);
std::cout << "4. a is still a valid object:\n";
a.text = "recycled";
std::cout << " a.text = " << a.text << "\n";
std::cout << "5. returning by value -- elided, not moved:\n";
Message d = make("delta");
std::cout << "6. assignment:\n";
b = c; // c is an lvalue: copy
b = make("echo"); // a temporary: move
std::cout << "7. into a container:\n";
std::vector<Message> box;
box.reserve(2);
box.push_back(d); // lvalue: copy
box.push_back(std::move(d)); // explicit: move
return 0;
}
Output:
1. construct:
ctor alpha
2. copy from an lvalue:
COPY alpha
3. move from an lvalue, made explicit:
move alpha
4. a is still a valid object:
a.text = recycled
5. returning by value -- elided, not moved:
ctor delta
6. assignment:
COPY= alpha
ctor echo
move= echo
7. into a container:
COPY delta
move delta
Read the pattern in the output. You never asked for a move in cases 5, 6b or the temporaries — the compiler chose it, because a temporary has no future. The only places std::move appears are where you are handing over a named variable, and the compiler cannot know on its own that you are finished with it.
Case 5 is the surprise: returning by value produced no move at all, just a single constructor call. Since C++17 that elision is guaranteed for a returned temporary, so "return by value is slow" has not been true for a long time. Case 4 makes the other essential point: after being moved from, a is not destroyed or unusable — it is an empty but perfectly valid Message, and assigning a new value to it is entirely legal.
Technical Depth: Value Categories, std::move, and the Rules Around Them
Lvalues and rvalues
Every expression is either something with a name and an address you could take (an lvalue) or a value with no lasting identity (an rvalue):
std::string a = "x";
a // lvalue: it has a name
a + "y" // rvalue: a temporary
std::string("z") // rvalue
make("w") // rvalue: a function returning by value
std::move(a) // rvalue (specifically an xvalue): "treat a as expiring"
someVector[0] // lvalue: it refers to a real element
The distinction matters because it drives overload resolution. Given both overloads, the compiler picks by category:
void take(const std::string& s) { std::cout << "copy path\n"; }
void take(std::string&& s) { std::cout << "move path\n"; }
std::string name = "Ada";
take(name); // copy path -- lvalue
take("Ada"); // move path -- temporary
take(std::move(name)); // move path -- you said so
| Expression | Category | Binds to const T& | Binds to T&& |
|---|---|---|---|
| A named variable | lvalue | Yes | No |
| A temporary | rvalue | Yes | Yes (preferred) |
A function returning T | rvalue | Yes | Yes (preferred) |
A function returning T& | lvalue | Yes | No |
std::move(x) | xvalue | Yes | Yes (preferred) |
A const object | lvalue | Yes | No |
std::move moves nothing
This is the single most misleading name in the standard library. std::move is a cast, and it generates no instructions at all:
template <typename T>
constexpr std::remove_reference_t<T>&& move(T&& t) noexcept {
return static_cast<std::remove_reference_t<T>&&>(t);
}
It changes the category of the expression so that overload resolution selects the move constructor or move assignment. The actual stealing happens inside that constructor, which you wrote. std::move(x) on a type with no move operations simply resolves back to the copy — silently, and correctly.
The moved-from state
After a move, the source is valid but unspecified. You may safely destroy it, or assign a fresh value to it. You must not assume anything about what it contains:
std::vector<int> source{1, 2, 3};
std::vector<int> dest = std::move(source);
source.size(); // legal to call, but the value is unspecified
source.push_back(9); // legal
source[0]; // UB if it is empty -- and it is, in practice
source = {4, 5}; // the right way to reuse it
In every real implementation source ends up empty, because a container's move constructor has to be O(1) and cannot allocate. Relying on that is still relying on something the standard does not promise. When you write your own move operations, put the source into a definite state anyway — nullptr, zero, empty — because that is what makes your own destructor safe.
The rule of five, and the trap that comes with it
Declaring any one of the five special members changes what the compiler generates for the others:
| You declare | Compiler still generates |
|---|---|
| Nothing | All five |
| A destructor | Copy operations (deprecated), no move operations |
| A copy constructor | No move operations |
| A move constructor | No copy operations (they are deleted) |
| All five | Nothing implicitly |
That second row is the trap. A class that writes a destructor to release a resource silently loses its move operations, so every "move" quietly becomes a deep copy — or fails to compile if the copy is deleted. Hence the rule of five: if you write one of destructor, copy constructor, copy assignment, move constructor, move assignment, consider all five.
The better answer is usually the rule of zero: hold std::vector, std::string and std::unique_ptr members, write none of the five, and the compiler generates correct move operations for free.
class Report {
std::string title;
std::vector<double> rows;
std::unique_ptr<Index> index;
// no destructor, no copy, no move -- and moving works perfectly
};
When you do want the defaults explicitly, say so:
Widget(Widget&&) noexcept = default;
Widget& operator=(Widget&&) noexcept = default;
Widget(const Widget&) = delete;
Widget& operator=(const Widget&) = delete;
noexcept is not decoration
std::vector reallocates by moving its elements into the new block. If a move could throw halfway through, the vector would be left with elements in neither buffer and no way to recover — so it only uses the move constructor when that constructor is declared noexcept. Otherwise it copies every element, and your move constructor is never called at all.
Photo(Photo&&) noexcept; // vector growth uses moves
Photo(Photo&&); // vector growth falls back to copies
A move constructor that only steals pointers and resets the source genuinely cannot throw, so marking it noexcept is honest as well as necessary.
Copy elision, and the "pessimising move"
std::vector<int> good() { std::vector<int> v{1, 2}; return v; } // elided
std::vector<int> bad() { std::vector<int> v{1, 2}; return std::move(v); } // forces a move
std::vector<int> worse() { return std::move(std::vector<int>{1, 2}); } // pointless
Returning a local by name lets the compiler construct it directly in the caller's storage — no move, no copy. Writing return std::move(v) disables that optimisation and substitutes a move, which is slower than nothing. The rule is short: never std::move a return value. The exceptions are narrow: returning a member (return std::move(member_);), or returning a by-value parameter, where elision does not apply.
std::move on a const object silently copies
const std::string master = "big";
std::string copy = std::move(master); // compiles, and copies
std::move(master) is a const std::string&&, which cannot bind to std::string&&, so overload resolution falls back to the copy constructor. There is no warning. If a move you expected is not happening, check whether the source is const.
The pass-by-value-and-move idiom
For a constructor or setter that stores its argument, take it by value and move it into place:
class User {
std::string name;
public:
User(std::string n) : name(std::move(n)) {} // one copy OR one move, never two
void setName(std::string n) { name = std::move(n); }
};
User a("literal"); // temporary -> moved in: zero copies
std::string existing = "Ada";
User b(existing); // one copy into the parameter, then moved
Taking const std::string& and then assigning would always copy; taking both const& and && overloads doubles the code. By value plus std::move is one function that is optimal for temporaries and no worse than the alternative for lvalues.
Forwarding references are not rvalue references
void sink(std::string&& s); // rvalue reference: temporaries only
template <typename T>
void relay(T&& value) { // FORWARDING reference: binds to anything
sink(std::forward<T>(value)); // preserves the caller's category
}
T&& in a deduced template context is a forwarding reference: given an lvalue it deduces T = std::string&, given an rvalue it deduces T = std::string. Inside the function, value has a name and is therefore an lvalue — so passing it on unchanged would always copy. std::forward<T> restores the original category. Use std::move when you know you are done with something; use std::forward only in a template that is passing a deduced argument through.
When moving buys you nothing
| Type | Moving a value of it |
|---|---|
int, double, pointers, small structs of those | Identical to a copy; std::move is noise |
std::string under the SSO limit (~15 chars) | Identical to a copy — the characters live in the object |
std::string above it, std::vector, std::map | O(1) pointer transfer instead of O(n) |
std::unique_ptr | The only way to transfer it; copying is deleted |
std::shared_ptr | Avoids an atomic increment and decrement |
std::array<int, 100> | Identical to a copy — the storage is inside the object |
Moving helps exactly when an object owns something elsewhere. For anything whose bytes are the whole value, a move is a copy with extra syntax.
Real World Example: A Photo Library That Counts Its Own Copies
Photo owns a raw pixel buffer, so it has to implement all five special members by hand — the case where you actually write move operations rather than letting the compiler generate them. Two global counters make the compiler's choices visible.
#include <iostream>
#include <string>
#include <vector>
#include <utility>
#include <cstring>
struct Stats { int copies = 0; int moves = 0; };
Stats stats; // instrumentation only
std::string report() {
return "copies=" + std::to_string(stats.copies) + " moves=" + std::to_string(stats.moves);
}
class Photo {
std::string name_;
std::size_t bytes_ = 0;
unsigned char* pixels_ = nullptr;
public:
Photo(std::string name, std::size_t bytes)
: name_(std::move(name)), bytes_(bytes), pixels_(new unsigned char[bytes]{}) {}
~Photo() { delete[] pixels_; }
Photo(const Photo& other)
: name_(other.name_), bytes_(other.bytes_),
pixels_(new unsigned char[other.bytes_]) {
std::memcpy(pixels_, other.pixels_, bytes_);
++stats.copies;
}
Photo& operator=(const Photo& other) {
if (this == &other) return *this;
unsigned char* fresh = new unsigned char[other.bytes_]; // allocate before freeing
std::memcpy(fresh, other.pixels_, other.bytes_);
delete[] pixels_;
pixels_ = fresh;
bytes_ = other.bytes_;
name_ = other.name_;
++stats.copies;
return *this;
}
Photo(Photo&& other) noexcept
: name_(std::move(other.name_)), bytes_(other.bytes_), pixels_(other.pixels_) {
other.pixels_ = nullptr; // a definite state, not just "unspecified"
other.bytes_ = 0;
++stats.moves;
}
Photo& operator=(Photo&& other) noexcept {
if (this == &other) return *this;
delete[] pixels_; // release what we already hold
name_ = std::move(other.name_);
bytes_ = other.bytes_;
pixels_ = other.pixels_;
other.pixels_ = nullptr;
other.bytes_ = 0;
++stats.moves;
return *this;
}
const std::string& name() const { return name_; }
std::size_t bytes() const { return bytes_; }
bool empty() const { return pixels_ == nullptr; }
};
Photo load(std::string name, std::size_t bytes) {
return Photo(std::move(name), bytes); // elided in C++17: no move counted
}
void archive(Photo p) { // by value: the caller decides copy or move
std::cout << " archived " << p.name() << " (" << p.bytes() << " bytes)\n";
}
int main() {
std::vector<Photo> album;
album.reserve(4); // no reallocation, so no hidden moves
album.push_back(load("sunset.png", 1200)); // temporary -> moved
album.push_back(load("dunes.png", 800)); // temporary -> moved
Photo portrait("portrait.png", 2000);
album.push_back(portrait); // lvalue -> copied
album.push_back(std::move(portrait)); // explicit -> moved
std::cout << "built album: " << report() << "\n";
std::cout << "portrait now holds " << portrait.bytes()
<< " bytes, empty=" << portrait.empty() << "\n\n";
Photo thumb("thumb.png", 50);
Photo scratch("scratch.png", 10);
scratch = thumb; // copy assignment
scratch = std::move(thumb); // move assignment
std::cout << "after assignments: " << report() << "\n";
std::cout << "scratch is now " << scratch.name()
<< " at " << scratch.bytes() << " bytes\n\n";
std::vector<Photo> backup = std::move(album); // moves the vector, not the photos
std::cout << "moved the vector: " << report() << "\n";
std::cout << "album.size()=" << album.size()
<< ", backup.size()=" << backup.size() << "\n\n";
archive(std::move(backup.back()));
std::cout << "after archive: " << report() << "\n\n";
const Photo master("master.png", 4000);
Photo derived = std::move(master); // const: silently a COPY
std::cout << "std::move on a const object: " << report() << "\n";
std::cout << "master still holds " << master.bytes() << " bytes\n";
return 0;
}
Output:
built album: copies=1 moves=3
portrait now holds 0 bytes, empty=1
after assignments: copies=2 moves=4
scratch is now thumb.png at 50 bytes
moved the vector: copies=2 moves=4
album.size()=0, backup.size()=4
archived portrait.png (2000 bytes)
after archive: copies=2 moves=5
std::move on a const object: copies=3 moves=5
master still holds 4000 bytes
Four photos went into the album and only one was copied — the one pushed from a named variable that the program still intended to use. That is the whole economics of move semantics in one line of output. Note that neither call to load produced a move either: since C++17, return Photo(...) constructs the object directly in the caller's storage, so the pair of pushes cost two moves in total rather than four.
The two write-both-forms operations show the asymmetry that trips people up. The copy assignment allocates fresh before it calls delete[], so a throwing new leaves the object exactly as it was; the move assignment can free first, because nothing that follows can throw. Both begin with a self-assignment guard, and both leave the source of a move in a definite state — nullptr and 0 — rather than merely an unspecified one. That is why the destructor is safe afterwards, and why portrait.bytes() reliably prints 0 instead of whatever happened to be left behind. Both move operations are noexcept, which is what makes them usable during a std::vector reallocation at all.
std::vector<Photo> backup = std::move(album); is the most instructive line in the program: the counters do not budge. Moving a vector transfers three pointers, and the four Photo objects never learn it happened — they are not touched, relocated, or reconstructed. The container's move is O(1) no matter how much it contains. album is left empty afterwards, which every implementation does and which the standard describes only as "valid but unspecified", so the safe reading is that album may now be reused but must not be assumed to hold anything.
archive(std::move(backup.back())) shows the by-value parameter earning its keep. archive takes a Photo by value, and the caller chose to move into it, so the transfer cost nothing; had the caller passed backup.back() without std::move, the same function would have deep-copied two kilobytes. One signature, and the decision left where it belongs. The element left in backup is now empty, which is legal but is exactly the kind of thing a comment should say out loud in production code.
The last two lines are the quiet trap. std::move(master) on a const Photo produces a const Photo&&, which cannot bind to Photo&&, so the copy constructor wins — the counter rises to copies=3 and master is untouched. Nothing warns you. If a class of yours seems never to be moved, the first thing to check is whether the source was const.
Worth stating plainly: almost none of this code needs to exist. Replace unsigned char* pixels_ with std::vector<unsigned char> and all five special members can be deleted from the class, because the compiler will generate move operations that do precisely what the handwritten ones do. The version above is what the inside of std::vector looks like, written out once so that the generated version is no longer mysterious.
Common Mistakes
- Writing a destructor and expecting moves to still work. Declaring a destructor suppresses the implicit move operations, so every "move" becomes a deep copy. Declare all five, or hold members that manage themselves.
return std::move(local);This disables copy elision and makes the function slower. Return the local by name.- Omitting
noexcepton move operations, after whichstd::vectorgrowth copies instead of moving and the move constructor is never called. - Using an object after moving from it. It is valid but unspecified; reading a moved-from
std::string's contents or indexing a moved-from vector is a bug. Assign a fresh value first. std::moveon aconstobject. Compiles, copies, warns about nothing.std::movein a template wherestd::forwardwas needed.std::move(value)insiderelay(T&& value)steals from the caller's lvalue.- Forgetting the self-assignment guard, so
p = std::move(p)frees the buffer and then stores the dangling pointer back. std::moveon anint, a pointer, or a smallstruct. It does nothing but add noise.- Freeing before allocating in copy assignment. If
newthen throws, the object is left holding a dangling pointer.
Best Practices
- Prefer the rule of zero: hold
std::string,std::vectorandstd::unique_ptrmembers and write none of the five. - When you must write them, write all five, mark both move operations
noexcept, and leave moved-from sources in a definite state. - Take constructor and setter arguments by value and
std::movethem into members. - Never
std::movea return value; return locals by name and let elision work. - Use
std::moveonly for named objects you are finished with, andstd::forward<T>only inside templates with a deducedT&&. - Call
reservebefore a run ofpush_backto avoid reallocation moves altogether. - Use
emplace_back(args...)to construct in place when you have the arguments rather than the object. - If a move you expected is not happening, check for a
constsource, a missingnoexcept, or a user-declared destructor.
Practice Exercises
- Take the
Photoclass above and rewrite it holdingstd::vector<unsigned char>instead of a raw pointer. Delete all five special members, confirm it still compiles and behaves identically, then addstatic_assertchecks that it is move-constructible andnoexcept-movable. - Instrument a small
Bufferclass with counters, then push twelve of them into astd::vectorwithout callingreserve. Record how many moves happen, repeat withreserve(12), and then removenoexceptfrom the move constructor and record the numbers again. Explain all three results. - Write a
TaskQueueholdingstd::vector<std::unique_ptr<Task>>withvoid add(std::unique_ptr<Task>)andstd::unique_ptr<Task> take(). MakeTaskQueuemovable but not copyable, and demonstrate that a queue can be returned from a factory function and moved into a container while its tasks are never duplicated.