Move constructor
- C++ course
- Intermediate
- Lesson 102/116
- 5 min
Learn efficient transfer with the move constructor.
Move constructor
A move constructor steals the resource instead of copying it. Its signature is T(T&& other). This avoids expensive copies.
Example: Box(Box&& other) : content(std::move(other.content)) {}. Here the content member of other is moved with std::move into the new object's content. With a normal copy the string would be duplicated; moving just transfers ownership. The call Box b(std::move(a)); triggers the move constructor. The source is left empty.
When is the move constructor called?
The move constructor is called when a new object is initialized from an rvalue. This happens either with std::move or with a function returning a temporary.
Example: Box b(std::move(a)); and Box b = makeBox(); (if makeBox returns a Box) both call the move constructor. In the first case std::move explicitly turns a into an rvalue. In the second case the returned temporary is already an rvalue. The compiler makes this distinction automatically; if a move constructor is defined, moving is used instead of copying.
Practice Add a move constructor to the Box class
Add a move constructor to the Box class in the starting code: Box(Box&& other) : content(std::move(other.content)) {}. In main move a into b with std::move and print b.content with std::cout.
Starter code
#include <iostream>
#include <string>
#include <utility>
class Box {
public:
std::string content;
Box(std::string c) : content(c) {}
// Add the move constructor
};
int main() {
Box a("Hello");
// Move a into b and print b.content
return 0;
}Sample solution
#include <iostream>
#include <string>
#include <utility>
class Box {
public:
std::string content;
Box(std::string c) : content(c) {}
Box(Box&& other) : content(std::move(other.content)) {}
};
int main() {
Box a("Hello");
Box b(std::move(a));
std::cout << b.content;
return 0;
}Expected output
Hello
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Move constructor signature
Box(Box____ other) : content(std::move(other.content)) {}
Box(Box&& other) : content(std::move(other.content)) {}
Explanation: The move constructor takes an rvalue reference: Box(Box&& other).
2 Match each piece to its role
| Term | Meaning |
|---|---|
Box(Box&& other) |
Move constructor |
std::move(other.content) |
Content transfer |
T(T&&) |
Move signature |
Box b(std::move(a)) |
Move call |
3 What parameter type does the move constructor take?
Box(Box&& other);- rvalue reference (T&&) Correct answer
- lvalue reference (T&)
- By value (T)
- Pointer (T*)
Explanation: The move constructor takes an rvalue reference (T&&).