01 / 21

Using std::move

Learn how to transfer ownership of resources efficiently in C++ using move semantics: avoid unnecessary copies and write faster, cleaner code.

C++

What Problem Does std::move Solve?

In C++, when you assign one object to another, the compiler copies all its data by default. For large objects like vectors or strings with thousands of elements, this copy is expensive: it allocates new memory, copies every byte, then the original often gets destroyed anyway.

source [1, 2, 3, ... 1M] COPY dest [1, 2, 3, ... 1M] Slow: allocates + copies all data 2x memory usage during copy

Lvalues vs. Rvalues

Before understanding std::move, you need to know two fundamental value categories in C++. Every expression is either an lvalue or an rvalue.

Lvalue
Has a name and a persistent address in memory. You can take its address with &. Example: a variable like x.
Rvalue
A temporary value with no persistent identity. Cannot take its address. Example: the result of x + y or a literal like 42.
int x = 10; // x is an lvalue
int y = x + 5; // (x + 5) is an rvalue
std::string s = std::string("hi"); // s is an lvalue, std::string("hi") is an rvalue

Move Semantics: The Big Idea

Instead of copying data, move semantics let you transfer ownership of resources from one object to another. The source object is left in a valid but unspecified state: it no longer owns the data.

source ptr → [data...] MOVE dest ptr → [data...] source (after) ptr → nullptr No allocation needed! O(1) pointer swap

What std::move Actually Does

std::move does not move anything. It is a cast: it converts an lvalue into an rvalue reference, signaling to the compiler that the object may be "moved from." The actual move happens in the move constructor or move assignment operator.

// std::move is essentially this:
template<typename T>
T&& move(T& t) {
  return static_cast<T&&>(t);
}

The Core Rule

Use std::move(obj) when: 1. You will NOT use obj again after this line 2. The receiving type has a move constructor/assignment
std::vector<int> a = {1, 2, 3, 4, 5};

// We're done with 'a', transfer its data to 'b'
std::vector<int> b = std::move(a);

// Now: b == {1,2,3,4,5}, a is empty (moved-from)

Copy vs. Move

Copy Move
Operation Duplicates all data Transfers ownership
Performance \(O(n)\) : allocate + copy \(O(1)\) : pointer swap
Source after Unchanged (intact) Valid but empty
Syntax auto b = a; auto b = std::move(a);
Use when You still need the original You're done with the original

How to Apply std::move

1
Identify the object. Find a variable holding a large resource (vector, string, unique_ptr) that you no longer need.
2
Verify it won't be used again. After the move, the object must not be read or relied upon (only destroyed or reassigned).
3
Wrap in std::move(). Pass the variable through std::move(obj) at the point of transfer.
4
Ensure the receiver supports moves. Standard library types (vector, string, unique_ptr) all have move constructors. Custom classes need explicit move constructors.

Example 1: Moving a String

std::string greeting = "Hello, World!";

// We want to store greeting in a vector
std::vector<std::string> messages;

// Without move: copies the string (slow for big strings)
messages.push_back(greeting);

// With move: transfers the string's buffer (fast!)
messages.push_back(std::move(greeting));

// greeting is now empty: ""

Example 2: Moving into a Function

void processData(std::vector<int> data) {
  // 'data' now owns the vector
  // ... do work ...
}

std::vector<int> bigVec(1000000, 42);

// BAD: copies 1 million ints into the parameter
processData(bigVec);

// GOOD: moves the vector (if we're done with bigVec)
processData(std::move(bigVec));
// bigVec is now empty

Example 3: unique_ptr Requires Move

std::unique_ptr cannot be copied at all: it represents exclusive ownership. The only way to transfer it is with std::move.

auto ptr = std::make_unique<Widget>();

// auto ptr2 = ptr; // ERROR! Cannot copy unique_ptr

auto ptr2 = std::move(ptr); // OK: ownership transferred

// ptr is now nullptr
// ptr2 owns the Widget

When Not to Use std::move

The compiler already optimizes return values. Using std::move on a return statement can actually prevent a powerful optimization called Return Value Optimization (RVO).

// BAD: prevents RVO!
std::vector<int> makeVec() {
  std::vector<int> v = {1, 2, 3};
  return std::move(v); // Don't do this!
}

// GOOD: compiler applies RVO (zero copies, zero moves)
std::vector<int> makeVec() {
  std::vector<int> v = {1, 2, 3};
  return v; // RVO: constructs directly in caller
}

Move Constructor & Assignment

For std::move to work on your own classes, you need to define a move constructor and/or move assignment operator. They take an rvalue reference (\(T\&\&\)).

class Buffer {
  int* data;
  std::size_t size;
public:
  // Move constructor
  Buffer(Buffer&& other) noexcept
    : data(other.data), size(other.size) {
    other.data = nullptr;
    other.size = 0;
  }

  // Move assignment operator
  Buffer& operator=(Buffer&& other) noexcept {
    if (this != &other) {
      delete[] data;
      data = other.data; size = other.size;
      other.data = nullptr; other.size = 0;
    }
    return *this;
  }
};

std::move Lifecycle

lvalue: obj owns resources std::move(obj) rvalue reference \(T\&\&\) (cast only) move ctor / move assign new_owner owns resources now obj (moved-from) valid but empty Remember: std::move = cast (step 1) actual move = step 2

Common Mistakes

✕ Using After Move
Reading a variable after std::move yields unspecified values. The object is in a valid but emptied state: don't rely on its contents.
✕ Moving in Return
Writing return std::move(x); for a local variable defeats RVO. Just return x; is faster.
✕ Moving Const Objects
std::move(const_obj) silently falls back to a copy. A const rvalue ref matches the copy constructor.

Summary Table

Scenario Use std::move? Why
Transfer a local into a container ✓ Yes Avoids copy of large data
Pass to a by-value parameter ✓ Yes Triggers move constructor
Transfer unique_ptr ✓ Yes Required: cannot copy
Return local from function ✕ No RVO is better: zero-cost
Move a const object ✕ No Silently copies instead
Move an int/float ✕ No Trivial types: no benefit

Question 1 of 5

What does std::move actually do at the language level?

Question 2 of 5

After std::vector<int> b = std::move(a);, what is the state of a?

Question 3 of 5

Why should you not write return std::move(localVar); in a function?

Question 4 of 5

What happens when you call std::move on a const object?

Question 5 of 5

What happens when you try to compile the code above?