Copying a string with a 40-character title means allocating a new buffer and copying 40 bytes. Copying a vector of 1000 tasks means doing that a thousand times. Often the copy is pointless: a function builds a title in a local variable and hands it to a task, and the local is never used again. What you want is to hand over the buffer itself, leaving the source empty-handed. That is a move.
Standard strings and containers support moving: the destination takes over the source's heap memory, which costs a few pointer assignments however large the contents are. The compiler moves automatically from values that are about to disappear, such as temporaries. For a named variable you are finished with, you say so with std::move from <utility>. This lesson shows what std::move really does, when a move silently becomes a copy, and what you may do with an object after moving from it.
Predict and run
destination is built from std::move(source), and then source gets a new value. What is printed?
#include <iostream>
#include <string>
#include <utility>
int main() {
std::string source = "Read";
std::string destination = std::move(source);
source = "Reuse";
std::cout << destination << " " << source << "\n";
return 0;
}Check your prediction
Read Reusedestination now owns "Read". Assigning "Reuse" to source gives it a fresh, known value, so printing it afterward is fine. Printing source before that assignment would not have a portable answer, as explained below.
std::move is a cast, not an action
Expressions in C++ have a value category. Roughly, an lvalue names an object that keeps existing, like a variable, and an rvalue is a value about to disappear, like the temporary result of std::string("a") + "b". Initializing from an lvalue copies, because the source is still needed. Initializing from an rvalue may move, because nobody can observe the source afterward.
std::move(x) does not move anything. It is a cast that turns the lvalue x into an rvalue, which says "I am finished with x; you may take its contents". The move happens only if the destination's type has a move constructor or move assignment that accepts it. Two common cases quietly copy instead:
- A
constsource. A move must modify the source, sostd::moveof aconstobject selects the copy constructor. No error, no warning. - A type with no move operations. Declaring your own destructor or copy operations stops the compiler from generating moves, so "moving" such a type copies. Another reason to follow the rule of zero.
The type below counts its copies and moves so you can see which one each line performs:
#include <iostream>
#include <string>
#include <utility>
#include <vector>
struct Tracked {
inline static int copies = 0;
inline static int moves = 0;
std::string name;
explicit Tracked(std::string text) : name(std::move(text)) {}
Tracked(const Tracked& other) : name(other.name) { ++copies; }
Tracked(Tracked&& other) noexcept : name(std::move(other.name)) { ++moves; }
};
int main() {
Tracked a("Read");
Tracked b = a;
Tracked c = std::move(a);
const Tracked d("Fixed");
Tracked e = std::move(d);
std::vector<Tracked> shelf;
shelf.reserve(2);
shelf.push_back(Tracked("Temp"));
std::cout << "copies " << Tracked::copies << ", moves " << Tracked::moves << "\n";
std::cout << b.name << " " << c.name << " " << e.name << " " << shelf[0].name << "\n";
return 0;
}copies 2, moves 2
Read Read Fixed Tempb is a copy and c a move. e is a copy even though the line says std::move, because d is const. The temporary passed to push_back is moved into the vector. reserve(2) matters: without it, a later reallocation could add moves of its own and the counts would depend on the library's growth policy. Tracked writes its copy and move constructors only to count them; it is a measuring tool, not a model for ordinary classes. The move constructor is marked noexcept so containers trust it during reallocation.
Valid but unspecified
After a move, the source object is still a live object. Its destructor will run, and you may assign it a new value. For standard library types, the contents are valid but unspecified: a moved-from std::string is a real string, and in practice it is usually empty, but the standard does not promise that, so a program must not print it or test it and expect a particular answer. The safe uses of a moved-from object are:
- Assign it a new value, as the predict example did, and then use it normally.
- Let it be destroyed at the end of its scope.
The same applies to your own rule-of-zero classes, with an extra twist. A moved-from Task has a moved-from title, which may be empty, so it may break the task's own invariant. The project therefore treats moved-from tasks as "destroy or reassign only", and Tracker::add validates every task at its boundary rather than trusting that the object is still valid.
Practice
Your turn
Using the Tracked type above, write a Shelf class whose constructor reserves room for 10 items and whose void add(Tracked item) takes its parameter by value and moves it into a private vector. Reset both counters before each call and print what each kind of argument costs:
add(named): 1 copies, 1 moves
add(std::move(named)): 0 copies, 2 moves
add(Tracked("Temp")): 0 copies, 1 moves
Shelf holds 3After the second call, reassign named before using it again.
#include <iostream>
#include <string>
#include <utility>
#include <vector>
struct Tracked {
inline static int copies = 0;
inline static int moves = 0;
std::string name;
explicit Tracked(std::string text) : name(std::move(text)) {}
Tracked(const Tracked& other) : name(other.name) { ++copies; }
Tracked(Tracked&& other) noexcept : name(std::move(other.name)) { ++moves; }
Tracked& operator=(Tracked&& other) noexcept { name = std::move(other.name); return *this; }
};
// Write Shelf here.
int main() {
return 0;
}Hint 1: the idea
A by-value parameter is a new object. The caller's argument decides how it is built: copied from a named variable, moved from std::move(named), or built directly from a temporary. Inside add, the parameter is yours, so moving it into the vector is always right.
Hint 2: a first step
Write Shelf with only its constructor and an add that does nothing yet, plus a helper that sets Tracked::copies and Tracked::moves to 0. Make the first call, add(named), and print the counters: you should see 1 copies, 0 moves, which is the cost of building the parameter. Then make add store its parameter and see which counter goes up.
Show one solution
#include <iostream>
#include <string>
#include <utility>
#include <vector>
struct Tracked {
inline static int copies = 0;
inline static int moves = 0;
std::string name;
explicit Tracked(std::string text) : name(std::move(text)) {}
Tracked(const Tracked& other) : name(other.name) { ++copies; }
Tracked(Tracked&& other) noexcept : name(std::move(other.name)) { ++moves; }
Tracked& operator=(Tracked&& other) noexcept { name = std::move(other.name); return *this; }
};
class Shelf {
public:
Shelf() { items_.reserve(10); }
void add(Tracked item) { items_.push_back(std::move(item)); }
std::size_t size() const { return items_.size(); }
private:
std::vector<Tracked> items_;
};
void reset() { Tracked::copies = 0; Tracked::moves = 0; }
void report(const char* label) {
std::cout << label << ": " << Tracked::copies << " copies, " << Tracked::moves << " moves\n";
}
int main() {
Shelf shelf;
Tracked named("Read");
reset();
shelf.add(named);
report("add(named)");
reset();
shelf.add(std::move(named));
report("add(std::move(named))");
named = Tracked("Again");
reset();
shelf.add(Tracked("Temp"));
report("add(Tracked(\"Temp\"))");
std::cout << "Shelf holds " << shelf.size() << "\n";
return 0;
}add(named): 1 copies, 1 moves
add(std::move(named)): 0 copies, 2 moves
add(Tracked("Temp")): 0 copies, 1 moves
Shelf holds 3Passing a named object copies once into the parameter, which is unavoidable because the caller keeps it. Passing std::move(named) costs two cheap moves and no copy, and a temporary is built directly in the parameter (C++17 guarantees that), leaving one move. One by-value function serves all three callers well, which is why the project's Task::edit takes its title this way. The next lesson borrows text without copying or moving it at all.
Completion is saved in this browser only. It does not measure mastery.