Introduction & Syntax
Move Semantics · Study material
Move semantics in C++ let an object hand its resources – heap memory, file handles, sockets – to another object instead of copying them. Moving a vector of a million elements copies three pointers instead of a million integers. Introduced in C++11, move semantics is why modern C++ can return big objects from functions, store them in containers and pass them around cheaply, and it is why types like std::unique_ptr, std::thread and std::fstream can exist at all. The References topic introduced lvalues, rvalues and &&; this page goes all the way: writing move constructors, the rule of five and rule of zero, noexcept, moved-from states, copy elision, perfect forwarding and the mistakes interviewers love to ask about. Then practise with 60 questions – 20 MCQs, 20 predict-the-output puzzles, 10 find-the-error programs and 10 complete programs – verified on a real C++ compiler.
On this page
- Why moves are cheap and what std::move really does
- Writing a move constructor and move assignment (with std::exchange)
- Rule of five, rule of zero, and when the compiler generates moves
- noexcept moves and std::vector
- Copy elision, implicit move on return, and return std::move
- Sink parameters, perfect forwarding and std::forward
Copy versus move
A copy duplicates an object's resources; afterwards both objects are independent. A move transfers the resources: the target takes the source's pointer and the source is left in a valid but unspecified (usually empty) state. Moves are chosen automatically for rvalues – temporaries and expressions marked with std::move.
#include <iostream>
#include <string>
#include <utility>
#include <vector>
int main() {
std::vector<int> big(1'000'000, 7);
const int* before = big.data();
std::vector<int> copied = big; // copy: allocates and copies a million ints
std::vector<int> moved = std::move(big); // move: steals the buffer – just a few pointers
std::cout << (copied.data() != before) << ' ' // the copy has its own buffer
<< (moved.data() == before) << ' ' // the move took the SAME buffer
<< big.size() << ' ' << moved.size() << '\n';
return 0;
}
1 1 0 1000000
std::move does not move anything. It is just a cast to an rvalue reference (static_cast<T&&>) that says "you may steal from this". The actual moving happens in the move constructor or move assignment operator that overload resolution then selects.
Writing the special member functions: rule of five
A class that manages a raw resource needs all five special members: destructor, copy constructor, copy assignment, move constructor and move assignment. The move operations take the source's resource and reset the source so its destructor does nothing harmful. std::exchange(obj, new_value) sets a new value and returns the old one – exactly what a move needs.
#include <algorithm>
#include <cstddef>
#include <iostream>
#include <utility>
class Buffer {
std::size_t size_ = 0;
int* data_ = nullptr;
public:
explicit Buffer(std::size_t n) : size_(n), data_(new int[n]{}) {}
~Buffer() { delete[] data_; } // 1. destructor
Buffer(const Buffer& o) : size_(o.size_), data_(new int[o.size_]) { // 2. copy constructor: deep copy
std::copy(o.data_, o.data_ + size_, data_);
std::cout << "copy ";
}
Buffer& operator=(const Buffer& o) { // 3. copy assignment
if (this != &o) { Buffer tmp(o); swap(tmp); }
return *this;
}
Buffer(Buffer&& o) noexcept // 4. move constructor: steal
: size_(std::exchange(o.size_, 0)), data_(std::exchange(o.data_, nullptr)) {
std::cout << "move ";
}
Buffer& operator=(Buffer&& o) noexcept { // 5. move assignment
if (this != &o) {
delete[] data_;
size_ = std::exchange(o.size_, 0);
data_ = std::exchange(o.data_, nullptr);
}
return *this;
}
void swap(Buffer& o) noexcept { std::swap(size_, o.size_); std::swap(data_, o.data_); }
std::size_t size() const { return size_; }
};
int main() {
Buffer a(100);
Buffer b = a; // copy
Buffer c = std::move(a); // move: a is left empty
b = std::move(c); // move assignment
std::cout << "| " << a.size() << ' ' << b.size() << ' ' << c.size() << '\n';
return 0;
}
copy move | 0 100 0
Rule of zero
Better still, do not manage raw resources at all: build classes from members that already handle themselves (std::string, std::vector, std::unique_ptr). Then write none of the five – the compiler-generated versions copy and move member by member, and a move-only member makes the class move-only automatically.
#include <iostream>
#include <memory>
#include <string>
#include <type_traits>
#include <vector>
// Rule of zero: use members that already manage themselves; write NONE of the five
struct Student {
std::string name;
std::vector<int> marks;
};
// A member that is move-only makes the whole class move-only – automatically
struct Session {
std::string user;
std::unique_ptr<int> token;
};
int main() {
Student a{"Asha", {91, 88}};
Student b = std::move(a); // compiler-generated move: moves name and marks
std::cout << b.name << ' ' << b.marks.size() << ' ' << a.marks.size() << '\n';
std::cout << std::is_copy_constructible_v<Student> << std::is_move_constructible_v<Student>
<< std::is_copy_constructible_v<Session> << std::is_move_constructible_v<Session> << '\n';
return 0;
}
Asha 2 0 1101
When does the compiler generate move operations?
| If you declare… | Move constructor / assignment | Copy constructor / assignment |
|---|---|---|
| nothing | generated | generated |
| a destructor | not generated (copies are used instead) | generated (deprecated) |
| a copy constructor or copy assignment | not generated | the other one generated (deprecated) |
| a move constructor or move assignment | the other one not generated | deleted |
So adding just a logging destructor silently turns every move into a copy. If you declare any of the five, declare (or = default) them all.
noexcept moves and std::vector
When a vector grows, it must transfer its elements to new memory. To keep the strong exception guarantee (if something throws, the vector is unchanged), it moves elements only if the move constructor is noexcept; otherwise it copies them. Always mark move operations noexcept when they cannot throw – they almost never can.
#include <iostream>
#include <vector>
struct Safe {
Safe() = default;
Safe(const Safe&) { std::cout << "copy "; }
Safe(Safe&&) noexcept { std::cout << "move "; }
};
struct Risky {
Risky() = default;
Risky(const Risky&) { std::cout << "copy "; }
Risky(Risky&&) { std::cout << "move "; } // NOT noexcept
};
int main() {
std::vector<Safe> s;
s.reserve(1);
s.emplace_back();
std::cout << "[grow Safe] ";
s.emplace_back(); // reallocation: the old element is MOVED (noexcept)
std::cout << '\n';
std::vector<Risky> r;
r.reserve(1);
r.emplace_back();
std::cout << "[grow Risky] ";
r.emplace_back(); // reallocation: the old element is COPIED (strong exception guarantee)
std::cout << '\n';
return 0;
}
[grow Safe] move [grow Risky] copy
Copy elision and returning objects
Since C++17, returning a prvalue (return Tracker("x");) is guaranteed not to copy or move: the object is created directly in the caller's variable. Returning a named local is usually elided too (NRVO, optional), and when it is not, the compiler moves it automatically. So never write return std::move(local); – it prevents elision and is a pessimisation.
#include <iostream>
#include <string>
struct Tracker {
std::string name;
explicit Tracker(std::string n) : name(std::move(n)) {}
Tracker(const Tracker& o) : name(o.name) { std::cout << "[copy] "; }
Tracker(Tracker&& o) noexcept : name(std::move(o.name)) { std::cout << "[move] "; }
};
// Returning a prvalue: C++17 GUARANTEES no copy and no move – the object is built in place
Tracker make() { return Tracker("built"); }
// Returning a parameter: cannot be elided, but it is moved automatically (implicit move)
Tracker pass_through(Tracker t) { return t; }
int main() {
Tracker a = make(); // nothing printed
std::cout << a.name << '\n';
Tracker b = pass_through(Tracker("x")); // [move] – the return of the parameter
std::cout << b.name << '\n';
Tracker c = std::move(a); // explicit move
std::cout << c.name << " '" << a.name << "'\n";
return 0;
}
built [move] x [move] built ''
Sink parameters
A function that stores its argument can take it by value and then std::move it into place. Callers with an lvalue pay one copy, callers with an rvalue pay only moves – one function instead of two overloads.
#include <iostream>
#include <string>
#include <utility>
#include <vector>
struct Name {
std::string s;
Name(const char* p) : s(p) {}
Name(const Name& o) : s(o.s) { std::cout << "copy "; }
Name(Name&& o) noexcept : s(std::move(o.s)) { std::cout << "move "; }
};
class Roster {
std::vector<Name> names_;
public:
Roster() { names_.reserve(10); }
// Sink parameter: take BY VALUE, then move into place – one function serves lvalues and rvalues
void add(Name n) { names_.push_back(std::move(n)); }
std::size_t size() const { return names_.size(); }
};
int main() {
Roster r;
Name asha = "Asha";
std::cout << "lvalue: "; r.add(asha); // copy into the parameter, then move
std::cout << "\nrvalue: "; r.add(std::move(asha)); // move, move
std::cout << "\nliteral: "; r.add("Ravi"); // constructed in the parameter, then move
std::cout << "\n" << r.size() << '\n';
return 0;
}
lvalue: copy move rvalue: move move literal: move 3
Perfect forwarding
In a template, T&& with a deduced T is a forwarding reference: through reference collapsing it becomes U& for lvalues and U&& for rvalues. Inside the function the parameter has a name, so it is an lvalue; std::forward<T>(x) restores the original category. This is how emplace_back, make_unique and std::thread pass arguments through unchanged.
#include <iostream>
#include <string>
#include <utility>
void sink(const std::string& s) { std::cout << "lvalue(" << s << ") "; }
void sink(std::string&& s) { std::cout << "rvalue(" << s << ") "; }
// T&& with a deduced T is a FORWARDING reference: it binds to anything
template <typename T>
void relay_wrong(T&& x) { sink(x); } // x has a name → always an lvalue
template <typename T>
void relay(T&& x) { sink(std::forward<T>(x)); } // keeps the original value category
int main() {
std::string name = "Asha";
relay_wrong(name); relay_wrong(std::string("tmp"));
std::cout << '\n';
relay(name); relay(std::string("tmp")); relay(std::move(name));
std::cout << '\n';
return 0;
}
lvalue(Asha) lvalue(tmp) lvalue(Asha) rvalue(tmp) rvalue(Asha)
Common mistakes
- Using an object after moving from it as if it still had its value – only assign to it or destroy it.
- std::move on a const object – the copy constructor is chosen silently.
- return std::move(local) – blocks copy elision.
- Move operations without noexcept – vectors copy instead of moving.
- Declaring a destructor only – the implicit moves disappear.
- Forgetting to reset the source in a hand-written move – double delete.
- std::move instead of std::forward on a forwarding reference – steals from the caller's lvalues.
Key points to remember
- A move transfers resources; std::move is only a cast to T&&.
- Moved-from objects are valid but unspecified: assign or destroy them.
- Prefer the rule of zero; otherwise implement all five special members.
- Mark move constructor and move assignment noexcept.
- Return locals by name; never return std::move(local).
- Sink parameters: pass by value, then std::move.
- Use std::forward<T> with forwarding references T&&.
Frequently asked questions
Is a move always faster than a copy?
Only for types that own resources elsewhere (heap memory, handles). For an int, a std::array or a small struct of numbers, moving is the same as copying.
What state is a moved-from std::string or std::vector in?
Valid but unspecified. In practice they are usually empty, but the only guarantees are that you may destroy them, assign to them, or call functions without preconditions (like clear() or size()).
What is the difference between std::move and std::forward?
std::move always casts to an rvalue; std::forward<T> casts to an rvalue only if the original argument was an rvalue. Use move for objects you own, forward for forwarding references in templates.
Where can I learn more?
Read C++ Move Semantics and C++ References, then practise with the exercises below.