# Move constructors

> C++ Atlas: `cppatlas.com/w/cpp/language/move_constructor` | Source: https://en.cppreference.com/w/cpp/language/move_constructor | Domain: Language | Standards: C++17, C++20, C++23

A move constructor is a constructor which can be called with an argument of the same class type and copies the content of the argument, possibly mutating the argument.

## 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)

A move constructor is a constructor which can be called with an argument of the same class type and copies the content of the argument, possibly mutating the argument.

### Syntax

- *class-name* `(`*parameter-list* `);`    (1)
- *class-name* `(`*parameter-list* `)` *function-body*    (2)
- *class-name* `(`*single-parameter-list* `) = default;`    (3)
- *class-name* `(`*parameter-list* `) = delete;`    (4)
- *class-name* `::`*class-name* `(`*parameter-list* `)` *function-body*    (5)
- *class-name* `::`*class-name* `(`*single-parameter-list* `) = default;`    (6)

- `class-name` - the class whose move constructor is being declared
- `parameter-list` - a non-empty parameter list satisfying all following conditions:

  - given the class type as `T`, the first parameter is of type `T&&`, `const T&&`, `volatile T&&` or `const volatile T&&`, and
  - either there are no other parameters, or all other parameters have default arguments
- `single-parameter-list` - a parameter list of only one parameter, which is of type `T&&`, `const T&&`, `volatile T&&` or `const volatile T&&` and does not have a default argument
- `function-body` - the function body of the move constructor

### Explanation

1) Declaration of a move constructor inside of class definition.

2-4) Definition of a move constructor inside of class definition.

  3) The move constructor is explicitly-defaulted.

  4) The move constructor is deleted.

5,6) Definition of a move constructor outside of class definition (the class must contain a declaration (1)).

  6) The move constructor is explicitly-defaulted.

```cpp
struct X
{
    X(X&& other); // move constructor
//  X(X other);   // Error: incorrect parameter type
};

union Y
{
    Y(Y&& other, int num = 1); // move constructor with multiple parameters
//  Y(Y&& other, int num);     // Error: `num` has no default argument
};
```

The move constructor is typically called when an object is initialized (by direct-initialization or copy-initialization) from rvalue (xvalue or prvalue) (until C++17) xvalue (since C++17) of the same type, including

- initialization: `T a = std::move(b);` or `T a(std::move(b));`, where `b` is of type `T`;
- function argument passing: `f(std::move(a));`, where `a` is of type `T` and `f` is `void f(T t)`;
- function return: `return a;` inside a function such as `T f()`, where `a` is of type `T` which has a move constructor.

When the initializer is a prvalue, the move constructor call is often optimized out (until C++17) never made (since C++17), see copy elision.

Move constructors typically transfer the resources held by the argument (e.g. pointers to dynamically-allocated objects, file descriptors, TCP sockets, thread handles, etc.) rather than make copies of them, and leave the argument in some valid but otherwise indeterminate state. Since move constructor doesn’t change the lifetime of the argument, the destructor will typically be called on the argument at a later point. For example, moving from a `std::string` or from a `std::vector` may result in the argument being left empty. For some types, such as `std::unique_ptr`, the moved-from state is fully specified.

### Implicitly-declared move constructor

If no user-defined move constructors are provided for a class type, and all of the following is true:

- there are no user-declared copy constructors;
- there are no user-declared copy assignment operators;
- there are no user-declared move assignment operators;
- there is no user-declared destructor.

Then the compiler will declare a move constructor as a non-explicit `inline public` member of its class with the signature `T::T(T&&)`.

A class can have multiple move constructors, e.g. both `T::T(const T&&)` and `T::T(T&&)`. If some user-defined move constructors are present, the user may still force the generation of the implicitly declared move constructor with the keyword `default`.

The implicitly-declared (or defaulted on its first declaration) move constructor has an exception specification as described in dynamic exception specification (until C++17) noexcept specification (since C++17).

### Implicitly-defined move constructor

If the implicitly-declared move constructor is neither deleted nor trivial, it is defined (that is, a function body is generated and compiled) by the compiler if ODR-use or needed for constant evaluation. For union types, the implicitly-defined move constructor copies the object representation (as by `std::memmove`). For non-union class types, the move constructor performs full member-wise move of the object's direct base subobjects and member subobjects, in their initialization order, using direct initialization with an xvalue argument. For each non-static data member of a reference type, the move constructor binds the reference to the same object or function to which the source reference is bound.

If this satisfies the requirements of a `constexpr` constructor (until C++23) `constexpr` function (since C++23), the generated move constructor is `constexpr`.

### Deleted move constructor

The implicitly-declared or explicitly-defaulted move constructor for class `T` is defined as deleted if `T` has a potentially constructed subobject of class type `M` (or possibly multi-dimensional array thereof) such that

- `M` has a destructor that is deleted or inaccessible from the copy constructor, or
- the overload resolution as applied to find `M`'s move constructor

  - does not result in a usable candidate, or
  - in the case of the subobject being a variant member, selects a non-trivial function.

Such a constructor is ignored by overload resolution (otherwise it would prevent copy-initialization from rvalue).

### Trivial move constructor

The move constructor for class `T` is trivial if all of the following is true:

- it is not user-provided (meaning, it is implicitly-defined or defaulted);
- `T` has no virtual member functions;
- `T` has no virtual base classes;
- the move constructor selected for every direct base of `T` is trivial;
- the move constructor selected for every non-static class type (or array of class type) member of `T` is trivial.

A trivial move constructor is a constructor that performs the same action as the trivial copy constructor, that is, makes a copy of the object representation as if by `std::memmove`. All data types compatible with the C language are trivially movable.

### Eligible move constructor

A move constructor is eligible if it is not deleted. (until C++20)

(since C++20):

A move constructor is eligible if all following conditions are satisfied:

- It is not deleted.
- Its associated constraints (if any) are satisfied.
- No move constructor whose associated constraints are satisfied is more constrained.

Triviality of eligible move constructors determines whether the class is an implicit-lifetime type, and whether the class is a trivially copyable type.

### Notes

To make the strong exception guarantee possible, user-defined move constructors should not throw exceptions. For example, `std::vector` relies on `std::move_if_noexcept` to choose between move and copy when the elements need to be relocated.

If both copy and move constructors are provided and no other constructors are viable, overload resolution selects the move constructor if the argument is an rvalue of the same type (an xvalue such as the result of `std::move` or a prvalue such as a nameless temporary (until C++17)), and selects the copy constructor if the argument is an lvalue (named object or a function/operator returning lvalue reference). If only the copy constructor is provided, all argument categories select it (as long as it takes a reference to const, since rvalues can bind to const references), which makes copying the fallback for moving, when moving is unavailable.

### Example

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

struct A
{
    std::string s;
    int k;

    A() : s("test"), k(-1) {}
    A(const A& o) : s(o.s), k(o.k) { std::cout << "move failed!\n"; }
    A(A&& o) noexcept :
        s(std::move(o.s)),       // explicit move of a member of class type
        k(std::exchange(o.k, 0)) // explicit move of a member of non-class type
    {}
};

A f(A a)
{
    return a;
}

struct B : A
{
    std::string s2;
    int n;
    // implicit move constructor B::(B&&)
    // calls A's move constructor
    // calls s2's move constructor
    // and makes a bitwise copy of n
};

struct C : B
{
    ~C() {} // destructor prevents implicit move constructor C::(C&&)
};

struct D : B
{
    D() {}
    ~D() {}           // destructor would prevent implicit move constructor D::(D&&)
    D(D&&) = default; // forces a move constructor anyway
};

int main()
{
    std::cout << "Trying to move A\n";
    A a1 = f(A()); // return by value move-constructs the target
                   // from the function parameter

    std::cout << "Before move, a1.s = " << std::quoted(a1.s)
        << " a1.k = " << a1.k << '\n';

    A a2 = std::move(a1); // move-constructs from xvalue
    std::cout << "After move, a1.s = " << std::quoted(a1.s)
        << " a1.k = " << a1.k << '\n';

    std::cout << "\nTrying to move B\n";
    B b1;

    std::cout << "Before move, b1.s = " << std::quoted(b1.s) << "\n";

    B b2 = std::move(b1); // calls implicit move constructor
    std::cout << "After move, b1.s = " << std::quoted(b1.s) << "\n";

    std::cout << "\nTrying to move C\n";
    C c1;
    C c2 = std::move(c1); // calls copy constructor

    std::cout << "\nTrying to move D\n";
    D d1;
    D d2 = std::move(d1);
}
```

Output:

```text
Trying to move A
Before move, a1.s = "test" a1.k = -1
After move, a1.s = "" a1.k = 0

Trying to move B
Before move, b1.s = "test"
After move, b1.s = ""

Trying to move C
move failed!

Trying to move D
```

### Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| CWG 1353 | C++11 | the conditions where defaulted move constructors are defined as deleted did not consider multi-dimensional array types | consider these types |
| CWG 1402 | C++11 | a defaulted move constructor that would call a non-trivial copy constructor was defined as deleted; a defaulted move constructor that is deleted still participated in overload resolution | allows call to such copy constructor; made ignored in overload resolution |
| CWG 1491 | C++11 | a defaulted move constructor of a class with a non-static data member of rvalue reference type was defined as deleted | not deleted in this case |
| CWG 2094 | C++11 | a volatile subobject made a defaulted move constructor non-trivial (CWG issue 496) | triviality not affected |
| CWG 2595 | C++20 | a move constructor was not eligible if there is another move constructor which is more constrained but does not satisfy its associated constraints | it can be eligible in this case |

### See also

- [converting constructor](https://en.cppreference.com/w/cpp/language/converting_constructor)
- [copy assignment](https://en.cppreference.com/w/cpp/language/as_operator)
- [copy constructor](https://en.cppreference.com/w/cpp/language/copy_constructor)
- [copy elision](https://en.cppreference.com/w/cpp/language/copy_elision)
- [default constructor](https://en.cppreference.com/w/cpp/language/default_constructor)
- [destructor](https://en.cppreference.com/w/cpp/language/destructor)
- [`explicit`](https://en.cppreference.com/w/cpp/language/explicit)
- [initialization](https://en.cppreference.com/w/cpp/language/initialization)
  - [aggregate initialization](https://en.cppreference.com/w/cpp/language/aggregate_initialization)
  - [constant initialization](https://en.cppreference.com/w/cpp/language/constant_initialization)
  - [copy initialization](https://en.cppreference.com/w/cpp/language/copy_initialization)
  - [default initialization](https://en.cppreference.com/w/cpp/language/default_initialization)
  - [direct initialization](https://en.cppreference.com/w/cpp/language/direct_initialization)
  - [initializer list](https://en.cppreference.com/w/cpp/language/initializer_list)
  - [list initialization](https://en.cppreference.com/w/cpp/language/list_initialization)
  - [reference initialization](https://en.cppreference.com/w/cpp/language/reference_initialization)
  - [value initialization](https://en.cppreference.com/w/cpp/language/value_initialization)
  - [zero initialization](https://en.cppreference.com/w/cpp/language/zero_initialization)
- [move assignment](https://en.cppreference.com/w/cpp/language/move_assignment)
- [`new`](https://en.cppreference.com/w/cpp/language/new)

## 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/language/move_constructor (cppreference.com), licensed under CC-BY-SA 3.0 and GFDL. Modified: converted to markdown, study notes added. Offline snapshot of 9 February 2025.