C++ Move Semantics
Learn how move constructors and move assignment let C++ transfer resources efficiently, avoiding unnecessary copies and unlocking high-performance code.
What Is a Resource?
In C++, objects often own resources: heap memory, file handles, network sockets, or GPU buffers. When we say an object "owns" a resource, we mean it is responsible for acquiring the resource and releasing it when done.
The Cost of Copying
The Move Idea
Instead of duplicating a resource, what if we transfer ownership? The new object steals the resource from the old one, and the old one is left in a valid but empty state.
Lvalues vs Rvalues
C++ distinguishes two categories of expressions. Understanding them is the key to understanding when the compiler can move.
The && Rvalue Reference
C++11 introduced a new reference type, the rvalue reference, written with &&. It can only bind to rvalues (temporaries), signaling: "I intend to move from this object."
The Move Constructor
A move constructor transfers resources from a dying object into a newly created one. Its signature takes an rvalue reference to the same type.
Move Assignment Operator
Move assignment transfers resources into an already existing object. It must first release the target's current resources, then steal from the source.
Copy vs Move: Side by Side
| Copy | Move | |
|---|---|---|
| Signature | \(\text{const } T\&\) | \(T\&\&\) |
| Source after | Unchanged | Valid but empty |
| Cost | \(O(n)\): deep clone | \(O(1)\): pointer swap |
| When used | Lvalue argument | Rvalue / std::move |
| noexcept? | Often not | Should be |
What std::move Really Does
std::move does not move anything. It is simply a cast that converts an lvalue into an rvalue reference, giving the compiler permission to move from it.
How to Apply Move Semantics
Example: MyString Move Constructor
Example: Returning by Value
When a function returns a local object, the compiler can automatically move it instead of copying: this is called Named Return Value Optimization (NRVO) or implicit move.
Example: push_back with Move
Common Mistakes
Summary Table
| Concept | Key Detail |
|---|---|
| Lvalue | Named, persistent, addressable |
| Rvalue | Temporary, about to die |
| \(T\&\&\) | Rvalue reference: binds to rvalues |
| Move Constructor | \(T(T\&\&)\) noexcept: steals resources |
| Move Assignment | \(T\& \text{ operator=}(T\&\&)\) noexcept |
| std::move(x) | Cast x to rvalue: gives permission to move |
| Rule of Five | Write all 5 special members or none |
Question 1 of 5
What does std::move(x) actually do at runtime?
Question 2 of 5
Which is the correct signature for a move constructor of class Widget?
Question 3 of 5
Why is it important to mark move operations as noexcept?
Question 4 of 5
What is the state of an object after it has been moved from?
Question 5 of 5
Given the function below, what is the best way to return the local vector?