# std::move

> C++ Atlas: `cppatlas.com/w/cpp/utility/move` | Source: https://en.cppreference.com/w/cpp/utility/move | Domain: Utility | Standards: C++11, C++14

std::move is used to indicate that an object t may be "moved from", i.e. allowing the efficient transfer of resources from t to another object.

## Executive Mental Model (Study Companion)

**Core Intuition:** T&& is a forwarding reference ONLY when T is a deduced template parameter of that exact function—not std::vector<T>&&.

- **Standard Era:** C++11 → C++20 → C++23
- **Primary ISO Clauses:** [dcl.ref], [temp.deduct.call], [class.copy.ctor], [utility.syn]
- **CppCon Talk Angle:** Show the exact 24-byte stack footprint of std::vector: copying duplicates the heap allocation, moving copies 3 pointers and nulls the source.
- **Common Audience Trap:** Forgetting noexcept on a custom move constructor, forcing std::vector::push_back to fall back to O(N) deep copies for exception safety.
- **Stage Takeaway:** Universal reference collapsing has one simple rule: '&' is infectious (& + anything = &). Only && + && yields &&.

## Memory Map Walkthrough: Stack/Heap Move Layout & Reference Collapsing Lab

Moving an owning container like std::vector does not move heap elements; it copies the 24-byte stack control block (begin, end, capacity pointers) into the destination and resets the source pointers to null in O(1) time. However, to preserve the strong exception guarantee during std::vector reallocation, std::vector calls std::move_if_noexcept—meaning if your user-defined move constructor is missing noexcept, vector silently copies every element instead of moving! Meanwhile, forwarding references (T&& or auto&&) leverage reference collapsing ([dcl.ref]): when an lvalue Widget passes to template<class T> void f(T&&), T deduces to Widget&, and Widget& && collapses to Widget&, letting std::forward<T> preserve the caller's exact value category.

### The noexcept move constructor cliff ([utility.move.if.noexcept] & [vector.capacity])

std::vector::push_back promises the strong exception guarantee: if reallocation fails halfway through migrating elements from the old buffer to the new buffer, the vector remains unchanged.

If moving element #50 out of 100 throws an exception, the old buffer already has 49 moved-from husks that cannot be rolled back. Therefore std::vector uses std::move_if_noexcept—it moves ONLY when the move constructor is noexcept (or when no copy constructor exists).

*noexcept unlocks fast vector growth:*
```cpp
struct Buffer {
    int* data = nullptr;
    Buffer(Buffer&& other) noexcept   // <-- omit noexcept and vector COPIES!
        : data(std::exchange(other.data, nullptr)) {}
    Buffer(const Buffer& other);
};
```

**Key takeaway:** Always mark user-defined move constructors and move assignment operators noexcept whenever they cannot throw.

### Forwarding reference vs. rvalue reference & collapsing ([temp.deduct.call] & [dcl.ref])

The syntax T&& means 'rvalue reference' everywhere EXCEPT when T is a deduced type parameter of that function template (or auto&&). Any cv-qualifier (const T&&) or wrapper (std::vector<T>&&) disables the forwarding-reference rule and becomes a plain rvalue reference.

When T&& IS a forwarding reference and receives an lvalue of type X, template deduction makes an intentional exception: T deduces to X&. Then reference collapsing fires: X& + && collapses to X&. Passing an rvalue deduces T = X, leaving X&&.

*Reference collapsing matrix:*
```cpp
template <class T>
void relay(T&& arg) {
    sink(std::forward<T>(arg));
}

Widget w;
relay(w);            // T = Widget&,  arg = Widget&  (lvalue)
relay(Widget{});     // T = Widget,   arg = Widget&& (xvalue after forward)
relay(std::move(w)); // T = Widget,   arg = Widget&&
```

**Key takeaway:** Any single & in a reference collapse (& &, & &&, && &) yields &; only && + && stays &&.

## Official Specification Summary (cppreference)

```cpp
// Defined in header <utility>

template< class T >
typename std::remove_reference<T>::type&& move( T&& t ) noexcept; // (since C++11) (until C++14)

template< class T >
constexpr std::remove_reference_t<T>&& move( T&& t ) noexcept; // (since C++14)
```

`std::move` is used to *indicate* that an object `t` may be "moved from", i.e. allowing the efficient transfer of resources from `t` to another object.

In particular, `std::move` produces an xvalue expression that identifies its argument `t`. It is exactly equivalent to a `static_cast` to an rvalue reference type.

### Parameters

- `t` - the object to be moved

### Return value

`static_cast<typename std::remove_reference<T>::type&&>(t)`

### Notes

The functions that accept rvalue reference parameters (including move constructors, move assignment operators, and regular member functions such as `std::vector::push_back`) are selected, by overload resolution, when called with rvalue arguments (either prvalues such as a temporary object or xvalues such as the one produced by `std::move`). If the argument identifies a resource-owning object, these overloads have the option, but aren't required, to *move* any resources held by the argument. For example, a move constructor of a linked list might copy the pointer to the head of the list and store `nullptr` in the argument instead of allocating and copying individual nodes.

Names of rvalue reference variables are lvalues and have to be converted to xvalues to be bound to the function overloads that accept rvalue reference parameters, which is why move constructors and move assignment operators typically use `std::move`:

```cpp
// Simple move constructor
A(A&& arg) : member(std::move(arg.member)) // the expression "arg.member" is lvalue
{}

// Simple move assignment operator
A& operator=(A&& other)
{
    member = std::move(other.member);
    return *this;
}
```

One exception is when the type of the function parameter is a forwarding reference (which looks like an rvalue reference to type template parameter), in which case `std::forward` is used instead.

Unless otherwise specified, all standard library objects that have been moved from are placed in a "valid but unspecified state", meaning the object's class invariants hold (so functions without preconditions, such as the assignment operator, can be safely used on the object after it was moved from):

```cpp
std::vector<std::string> v;
std::string str = "example";
v.push_back(std::move(str)); // str is now valid but unspecified
str.back(); // undefined behavior if size() == 0: back() has a precondition !empty()
if (!str.empty())
    str.back(); // OK, empty() has no precondition and back() precondition is met

str.clear(); // OK, clear() has no preconditions
```

Also, the standard library functions called with xvalue arguments may assume the argument is the only reference to the object; if it was constructed from an lvalue with `std::move`, no aliasing checks are made. However, self-move-assignment of standard library types is guaranteed to place the object in a valid (but usually unspecified) state:

```cpp
std::vector<int> v = {2, 3, 3};
v = std::move(v); // the value of v is unspecified
```

### Example

```cpp
#include <iomanip>
#include <iostream>
#include <string>
#include <utility>
#include <vector>

int main()
{
    std::string str = "Salut";
    std::vector<std::string> v;

    // uses the push_back(const T&) overload, which means
    // we'll incur the cost of copying str
    v.push_back(str);
    std::cout << "After copy, str is " << std::quoted(str) << '\n';

    // uses the rvalue reference push_back(T&&) overload,
    // which means no strings will be copied; instead, the contents
    // of str will be moved into the vector. This is less
    // expensive, but also means str might now be empty.
    v.push_back(std::move(str));
    std::cout << "After move, str is " << std::quoted(str) << '\n';

    std::cout << "The contents of the vector are {" << std::quoted(v[0])
              << ", " << std::quoted(v[1]) << "}\n";
}
```

Possible output:

```text
After copy, str is "Salut"
After move, str is ""
The contents of the vector are {"Salut", "Salut"}
```

### See also

- [`forward`](https://en.cppreference.com/w/cpp/utility/forward) (C++11): forwards a function argument and use the type template argument to preserve its value category (function template)
- [`move_if_noexcept`](https://en.cppreference.com/w/cpp/utility/move_if_noexcept) (C++11): converts the argument to an xvalue if the move constructor does not throw (function template)
- [`move`](https://en.cppreference.com/w/cpp/algorithm/move) (C++11): moves a range of elements to a new location (function template)

## Podcast Host Debate & Socratic Standard Traps

Use the prompts and tricky ISO standard questions below to guide a Socratic audio discussion:

- Break down what std::vector actually puts on the stack versus the heap, and why moving a million-element vector costs three pointer assignments.
- Tell the story of the missing noexcept move constructor and how std::move_if_noexcept quietly saves exception safety at the cost of speed.
- Clarify why Box<T>::push(T&&) is NOT a forwarding reference even though T&& looks identical.

### Trap 1: [vector.modifiers] & [utility.move.if.noexcept] (cppcon-stage)

Widget defines BOTH a copy constructor and a non-noexcept move constructor. What does std::vector<Widget>::push_back invoke on existing elements during buffer growth?

```cpp
struct Widget {
    Widget(const Widget&);
    Widget(Widget&&); // Note: NOT marked noexcept
};
```

A. The move constructor, because std::vector always moves existing items
B. The copy constructor, via std::move_if_noexcept, to preserve the strong exception guarantee
C. Compile error: move constructors must be noexcept to live in std::vector
D. memcpy bitwise relocation

**Standard Answer (B):** The copy constructor, via std::move_if_noexcept, to preserve the strong exception guarantee

**Why:** Because Widget has a copy constructor and its move constructor might throw, std::move_if_noexcept yields const Widget& so std::vector copies elements safely into the new buffer before freeing the old buffer.

### Trap 2: [temp.deduct.call] §13.10.3.2 (standard-lawyer)

Which function parameter is actually a forwarding (universal) reference?

A. template<class T> void f(std::vector<T>&& v);
B. template<class T> void f(const T&& v);
C. template<class T> struct Box { void push(T&& v); };
D. auto&& x = expr;

**Standard Answer (D):** auto&& x = expr;

**Why:** std::vector<T>&& and const T&& are plain rvalue references. Box<T>::push(T&&) is NOT deduced at the push() call site because T was already fixed by Box<T>! Only auto&& (or a template function's own deduced T&&) is a forwarding reference.

*CppCon speaker note:* Box<T>::push(T&&) is a notorious class-template surprise (think std::vector<T>::push_back(T&&)).

### Trap 3: [dcl.ref] §9.3.4.3 (subtle)

Given using LRef = int&; and using RRef = int&&;, what type does LRef&& collapse to?

A. int&&
B. int&
C. int
D. Ill-formed: references to references are always illegal

**Standard Answer (B):** int&

**Why:** While writing int& && directly in source is illegal, forming a reference to a reference through type aliases, decltype, or template substitution collapses via [dcl.ref]: if either reference is an lvalue reference (&), the result is an lvalue reference (int&).

### Trap 4: [lib.types.movedfrom] (subtle)

After std::string b = std::move(a);, what operations are guaranteed valid on the moved-from string a?

A. a is guaranteed to be empty (a.empty() == true)
B. Only destruction and reassignment are valid; calling a.clear() is UB
C. a is in a valid but unspecified state: all operations with no preconditions (like a.empty(), a.clear(), a = "new", ~string) are valid
D. Using a in any way after std::move is Undefined Behavior

**Standard Answer (C):** a is in a valid but unspecified state: all operations with no preconditions (like a.empty(), a.clear(), a = "new", ~string) are valid

**Why:** Standard library types leave moved-from objects in a valid but unspecified state ([lib.types.movedfrom]). While small-string optimization means a might NOT even be empty, you may safely inspect size(), call clear(), reassign, or destroy a.

---
Attribution: content from https://en.cppreference.com/w/cpp/utility/move (cppreference.com), licensed under CC-BY-SA 3.0 and GFDL. Modified: converted to markdown, study notes added. Offline snapshot of 9 February 2025.