Using std::move
Learn how to transfer ownership of resources efficiently in C++ using move semantics: avoid unnecessary copies and write faster, cleaner code.
What Problem Does std::move Solve?
In C++, when you assign one object to another, the compiler copies all its data by default. For large objects like vectors or strings with thousands of elements, this copy is expensive: it allocates new memory, copies every byte, then the original often gets destroyed anyway.
Lvalues vs. Rvalues
Before understanding std::move, you need to know two fundamental value categories in C++. Every expression is either an lvalue or an rvalue.
x.x + y or a literal like 42.int y = x + 5; // (x + 5) is an rvalue
std::string s = std::string("hi"); // s is an lvalue, std::string("hi") is an rvalue
Move Semantics: The Big Idea
Instead of copying data, move semantics let you transfer ownership of resources from one object to another. The source object is left in a valid but unspecified state: it no longer owns the data.
What std::move Actually Does
std::move does not move anything. It is a cast: it converts an lvalue into an rvalue reference, signaling to the compiler that the object may be "moved from." The actual move happens in the move constructor or move assignment operator.
template<typename T>
T&& move(T& t) {
return static_cast<T&&>(t);
}
The Core Rule
// We're done with 'a', transfer its data to 'b'
std::vector<int> b = std::move(a);
// Now: b == {1,2,3,4,5}, a is empty (moved-from)
Copy vs. Move
| Copy | Move | |
|---|---|---|
| Operation | Duplicates all data | Transfers ownership |
| Performance | \(O(n)\) : allocate + copy | \(O(1)\) : pointer swap |
| Source after | Unchanged (intact) | Valid but empty |
| Syntax | auto b = a; |
auto b = std::move(a); |
| Use when | You still need the original | You're done with the original |
How to Apply std::move
std::move(obj) at the point of transfer.Example 1: Moving a String
// We want to store greeting in a vector
std::vector<std::string> messages;
// Without move: copies the string (slow for big strings)
messages.push_back(greeting);
// With move: transfers the string's buffer (fast!)
messages.push_back(std::move(greeting));
// greeting is now empty: ""
Example 2: Moving into a Function
// 'data' now owns the vector
// ... do work ...
}
std::vector<int> bigVec(1000000, 42);
// BAD: copies 1 million ints into the parameter
processData(bigVec);
// GOOD: moves the vector (if we're done with bigVec)
processData(std::move(bigVec));
// bigVec is now empty
Example 3: unique_ptr Requires Move
std::unique_ptr cannot be copied at all: it represents exclusive ownership. The only way to transfer it is with std::move.
// auto ptr2 = ptr; // ERROR! Cannot copy unique_ptr
auto ptr2 = std::move(ptr); // OK: ownership transferred
// ptr is now nullptr
// ptr2 owns the Widget
When Not to Use std::move
The compiler already optimizes return values. Using std::move on a return statement can actually prevent a powerful optimization called Return Value Optimization (RVO).
std::vector<int> makeVec() {
std::vector<int> v = {1, 2, 3};
return std::move(v); // Don't do this!
}
// GOOD: compiler applies RVO (zero copies, zero moves)
std::vector<int> makeVec() {
std::vector<int> v = {1, 2, 3};
return v; // RVO: constructs directly in caller
}
Move Constructor & Assignment
For std::move to work on your own classes, you need to define a move constructor and/or move assignment operator. They take an rvalue reference (\(T\&\&\)).
int* data;
std::size_t size;
public:
// Move constructor
Buffer(Buffer&& other) noexcept
: data(other.data), size(other.size) {
other.data = nullptr;
other.size = 0;
}
// Move assignment operator
Buffer& operator=(Buffer&& other) noexcept {
if (this != &other) {
delete[] data;
data = other.data; size = other.size;
other.data = nullptr; other.size = 0;
}
return *this;
}
};
std::move Lifecycle
Common Mistakes
std::move yields unspecified values. The object is in a valid but emptied state: don't rely on its contents.return std::move(x); for a local variable defeats RVO. Just return x; is faster.std::move(const_obj) silently falls back to a copy. A const rvalue ref matches the copy constructor.Summary Table
| Scenario | Use std::move? | Why |
|---|---|---|
| Transfer a local into a container | ✓ Yes | Avoids copy of large data |
| Pass to a by-value parameter | ✓ Yes | Triggers move constructor |
| Transfer unique_ptr | ✓ Yes | Required: cannot copy |
| Return local from function | ✕ No | RVO is better: zero-cost |
| Move a const object | ✕ No | Silently copies instead |
| Move an int/float | ✕ No | Trivial types: no benefit |
Question 1 of 5
What does std::move actually do at the language level?
Question 2 of 5
After std::vector<int> b = std::move(a);, what is the state of a?
std::vector, this means it is empty. You can still destroy it or assign new values to it, but its old data now belongs to b.Question 3 of 5
Why should you not write return std::move(localVar); in a function?
std::move disables this optimization, forcing at least a move instead of getting RVO for free.Question 4 of 5
What happens when you call std::move on a const object?
std::move(const_obj) produces a \(\text{const}\ T\&\&\). Since move constructors take \(T\&\&\) (non-const), the overload resolution matches the copy constructor (\(\text{const}\ T\&\)) instead. The move is silently replaced by a copy: no error, no warning, just slower code.Question 5 of 5
Consider this code:
std::unique_ptr<Widget> a = std::make_unique<Widget>();
std::unique_ptr<Widget> b = a;
What happens when you try to compile the code above?
b = a; will not compile. You must write b = std::move(a); to transfer ownership.