01 / 21

C++ Move Semantics

Learn how move constructors and move assignment let C++ transfer resources efficiently, avoiding unnecessary copies and unlocking high-performance code.

C++ Programming

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.

Heap Memory
Allocated with new, freed with delete
File Handles
Opened with fopen, closed with fclose
Network Sockets
Connected then shut down on destruction

The Cost of Copying

Object A Heap Data [1 million ints] COPY Object B Heap Copy [1 million ints]
Cost: \(O(n)\)
4 MB duplicated!

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.

Object A Heap Data [1 million ints] nullptr Object B MOVE
Cost: \(O(1)\)
Just swap pointers!

Lvalues vs Rvalues

C++ distinguishes two categories of expressions. Understanding them is the key to understanding when the compiler can move.

Lvalue
Has a name and a persistent address. You can take its address with &. Lives beyond the current expression.
Rvalue
A temporary with no lasting identity. About to be destroyed. Safe to steal from.
std::string name = "Alice"; // name is an lvalue std::string greeting = name + " hi"; // (name + " hi") is an rvalue

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."

int& lref = x; // lvalue reference: binds to lvalue int&& rref = 42; // rvalue reference: binds to rvalue int&& bad = x; // ERROR: x is an lvalue!

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.

class Buffer { int* data; size_t size; public: // Move constructor Buffer(Buffer&& other) noexcept : data(other.data), size(other.size) { other.data = nullptr; // leave source empty other.size = 0; } };
1
Steal the source's pointer and size into the new object.
2
Null out the source so its destructor won't free the stolen memory.
3
Mark noexcept so the standard library can use it safely.

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.

Buffer& operator=(Buffer&& other) noexcept { if (this != &other) { delete[] data; // release own resource data = other.data; // steal size = other.size; other.data = nullptr; // null out source other.size = 0; } return *this; }

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.

std::vector<int> a = {1,2,3,4,5}; std::vector<int> b = std::move(a); // a is now empty! // a.size() == 0, b.size() == 5
a lvalue std::move(a) cast to T&& move constructor steals resources a: empty

How to Apply Move Semantics

1
Identify resource-owning classes: any class that manages heap memory, handles, or buffers.
2
Write a move constructor taking \(T\&\&\). Steal all resource pointers, null out the source.
3
Write a move assignment operator taking \(T\&\&\). Release own resources first, then steal, then null out.
4
Mark both noexcept so std::vector and other containers can use them during reallocation.
5
Use std::move() when you want to move from a named variable you no longer need.

Example: MyString Move Constructor

class MyString { char* buf; size_t len; public: // Move constructor MyString(MyString&& s) noexcept : buf(s.buf), len(s.len) { s.buf = nullptr; s.len = 0; } };
s (source) buf, len "Hello World" new object MOVE s.buf = nullptr, s.len = 0

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.

std::vector<int> makeData() { std::vector<int> v; v.reserve(1000000); // ... fill v ... return v; // move (or NRVO: no copy at all!) } auto result = makeData(); // zero copies

Example: push_back with Move

std::vector<std::string> names; std::string s = "a very long string..."; names.push_back(s); // COPIES s into the vector names.push_back(std::move(s)); // MOVES s into the vector // s is now empty: don't read it!
push_back(s)
Calls copy constructor. Allocates new memory. Copies every character. Slow.
push_back(move(s))
Calls move constructor. Swaps internal pointer. No allocation. Fast.

Common Mistakes

✕ Using after move
A moved-from object is in a valid but unspecified state. After std::move(x), do not rely on x's value: only assign to it or destroy it.
✕ Forgetting noexcept
std::vector will fall back to copying during reallocation if your move constructor is not marked noexcept.
✕ return std::move(local)
This prevents NRVO (copy elision). Just write return local; and let the compiler optimize.

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?

std::vector<int> build() { std::vector<int> v = {1,2,3}; return ???; }