std::move
- C++ course
- Intermediate
- Lesson 101/116
- 5 min
Learn move semantics with std::move.
Moving with std::move
std::move converts an lvalue into an rvalue. It does not move anything; it just makes moving possible. It comes from #include <utility>.
Example: std::string a = "Hello"; std::string b = std::move(a);. Here std::move(a) turns a into an rvalue and the move constructor of std::string is called. b now owns the "Hello" content; a is in a valid but unspecified state (most likely empty). This enables fast content transfer without copying.
State after std::move
After std::move the source object is in a valid but unspecified state. Its content may have been emptied; so you should not use the source object after moving.
Example: after std::string a = "Hello"; std::string b = std::move(a); you can safely assign a new value to a: a = "New";. But you should not read the old content of a. This is the core contract of move semantics: the source object is not destroyed, only its content is transferred. Assigning a new value is always safe.
Practice Move a string with std::move
The starting code has a string a containing "Hello". Move the content of a into b with std::move and print b with std::cout.
Starter code
#include <iostream>
#include <string>
#include <utility>
int main() {
std::string a = "Hello";
// Move the content of a into b and print b
return 0;
}Sample solution
#include <iostream>
#include <string>
#include <utility>
int main() {
std::string a = "Hello";
std::string b = std::move(a);
std::cout << b;
return 0;
}Expected output
Hello
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each piece to its role
| Term | Meaning |
|---|---|
std::move |
lvalue to rvalue |
&& |
rvalue reference |
#include <utility> |
Header file |
move constructor |
Stealing the resource |
2 Complete the std::move call
std::string b = std::____(a);
std::string b = std::move(a);
Explanation: std::move converts an lvalue to an rvalue.
3 What does std::move(a) do?
std::string a = "Hello";
std::string b = std::move(a);- Deletes a
- Copies a
- Returns the length of a
- Converts a to an rvalue Correct answer
Explanation: std::move converts a to an rvalue; it enables moving.