# Copy and move semantics

> How std::move grants permission without moving bytes, when user-declared special members suppress moves, why noexcept unlocks O(1) vector growth, and C++23 simpler implicit move.

- **Source:** C++ Atlas (https://cppatlas.com/topics/copy-and-move)
- **Track:** Value semantics
- **Estimated reading time:** 10 minutes
- **ISO C++ clauses:** [class.copy.ctor] (https://eel.is/c++draft/class.copy.ctor), [class.copy.assign] (https://eel.is/c++draft/class.copy.assign), [class.dtor] (https://eel.is/c++draft/class.dtor), [utility.move] (https://eel.is/c++draft/utility.move), [utility.exchange] (https://eel.is/c++draft/utility.exchange), [utility.move.if.noexcept] (https://eel.is/c++draft/utility.move.if.noexcept), [class.copy.elision] (https://eel.is/c++draft/class.copy.elision)
- **cppreference links:** [Copy constructors](https://en.cppreference.com/w/cpp/language/copy_constructor), [Copy assignment operator](https://en.cppreference.com/w/cpp/language/as_operator), [Move constructors](https://en.cppreference.com/w/cpp/language/move_constructor), [Move assignment operator](https://en.cppreference.com/w/cpp/language/move_assignment), [The rule of three/five/zero](https://en.cppreference.com/w/cpp/language/rule_of_three), [std::move](https://en.cppreference.com/w/cpp/utility/move), [std::move_if_noexcept](https://en.cppreference.com/w/cpp/utility/move_if_noexcept), [std::exchange](https://en.cppreference.com/w/cpp/utility/exchange)
- **Prerequisites:** value-categories

Copying duplicates an object's logical state so two independent owners emerge. Moving transfers ownership from an expiring source—typically copying a few stack pointers or descriptors and resetting the source to a benign empty state—without duplicating heap buffers. Misunderstanding where the compiler generates move operations, when `const` defeats them, or why `noexcept` governs `std::vector` performance turns intended moves into silent deep copies.

## What copying and moving actually do

Calling `std::move(x)` emits zero CPU instructions at runtime. Under `[utility.move]`, `std::move` is simply an unconditional cast to an rvalue reference (`static_cast<std::remove_reference_t<T>&&>(x)`), turning an lvalue expression into an **xvalue**. Only when that xvalue reaches a constructor or assignment operator—or a function overloaded on `T&&`—does any resource transfer actually occur.

> **Mental model.** `std::move` is a permission slip telling overload resolution that the source's resources may be pilfered; it never moves bytes by itself.

That permission slip is easily revoked by `const`. If `s` is declared `const std::string s = "payload";`, then `std::move(s)` produces `const std::string&&`. A move constructor takes non-const `std::string&&` because it must mutate the source, so `const std::string&&` cannot bind to it and silently binds to `const std::string&`, executing a full **copy constructor** instead.

> **Pitfall.** Calling `std::move` on a `const` object compiles cleanly and quietly invokes the copy constructor instead of moving, because `const T&&` cannot bind to a mutable `T&&` move parameter.

## Special member generation rules

C++ tracks six special member functions: default constructor, destructor, copy constructor, copy assignment operator, move constructor, and move assignment operator. Declaring one affects whether the compiler implicitly generates the others (`[class.copy.ctor]`, `[class.copy.assign]`).

| User declaration | Default ctor | Destructor | Copy operations | Move operations |
| --- | --- | --- | --- | --- |
| None | Defaulted | Defaulted | Defaulted | Defaulted |
| Any non-special ctor | Not declared | Defaulted | Defaulted | Defaulted |
| Destructor (`~T`) | Defaulted | User | Defaulted (deprecated if implicit) | Not declared (suppressed) |
| Copy ctor or copy assign | Same unless copy ctor | Defaulted | User / defaulted | Not declared (suppressed) |
| Move ctor or move assign | Same unless move ctor | Defaulted | Deleted | User / defaulted |

Two interactions catch experienced engineers off guard:

1. **Declaring a destructor suppresses implicit moves.** Even writing `~Buffer() = default;` in a class header disables implicit generation of both the move constructor and the move assignment operator. Any move request falls back to calling the copy constructor, silently turning O(1) transfers into O(N) deep copies—or failing to compile if a member such as `std::unique_ptr` is non-copyable.
2. **Declaring a move operation deletes copying.** Adding a custom move constructor (`T(T&&)`) marks both the copy constructor and copy assignment operator as implicitly `= delete` unless you explicitly declare or `= default` them.

Follow the **Rule of Zero** whenever possible: store resources in standard RAII wrappers (`std::unique_ptr`, `std::vector`, `std::string`) and declare none of the five ownership members. When building a low-level RAII handle directly, follow the **Rule of Five** and declare all five explicitly.

## Implementing move operations cleanly and exception-safely

A hand-written move operation must transfer ownership, leave the source safely destructible and assignable, and handle **self-move assignment** (`a = std::move(a)`, which generic sorting or partition algorithms can trigger). Standard library helper `std::exchange(obj, new_val)` from `<utility>` replaces a member with a null or sentinel value and returns its old value in one step:

```cpp
#include <cstddef>
#include <utility>

class Buffer {
    int* data_ = nullptr;
    std::size_t size_ = 0;

public:
    Buffer() = default;
    explicit Buffer(std::size_t n) : data_(n ? new int[n]{} : nullptr), size_(n) {}
    ~Buffer() { delete[] data_; }

    Buffer(const Buffer&) = delete;
    Buffer& operator=(const Buffer&) = delete;

    Buffer(Buffer&& other) noexcept
        : data_(std::exchange(other.data_, nullptr)),
          size_(std::exchange(other.size_, 0)) {}

    Buffer& operator=(Buffer&& other) noexcept {
        if (this == &other) {
            return *this;
        }
        delete[] data_;
        data_ = std::exchange(other.data_, nullptr);
        size_ = std::exchange(other.size_, 0);
        return *this;
    }
};
```

Wait before reading anything out of a moved-from standard library object. Under `[lib.types.movedfrom]`, a moved-from standard type is guaranteed to be in a **valid but unspecified state**: you can destroy it, assign a fresh value to it, or invoke precondition-free observers such as `clear()`, while assuming `vec.empty()` without checking is a logic bug unless a specific type documents it (like `std::unique_ptr`, which guarantees `get() == nullptr`).

## The noexcept cliff and std::move_if_noexcept

Containers such as `std::vector` enforce the **strong exception guarantee** during reallocation (`push_back` or `reserve`): if migrating elements from the old buffer to the new buffer throws an exception midway, the original vector must remain completely intact.

If moving element `k` threw after elements `0` through `k - 1` had already been moved from, rolling back could itself throw. To prevent data loss, `std::vector` moves elements via `std::move_if_noexcept` (`[utility.move.if.noexcept]`), which yields `T&&` **only** when `std::is_nothrow_move_constructible_v<T>` is true—or when `T` is not copy-constructible at all. Otherwise, it returns `const T&` and forces `std::vector` to copy every element!

```cpp
#include <type_traits>
#include <utility>

struct ThrowingMove {
    ThrowingMove(const ThrowingMove&) {}
    ThrowingMove(ThrowingMove&&) {} // Missing noexcept!
};

struct SafeMove {
    SafeMove(const SafeMove&) {}
    SafeMove(SafeMove&&) noexcept {}
};

static_assert(std::is_same_v<decltype(std::move_if_noexcept(std::declval<ThrowingMove&>())),
                             const ThrowingMove&>);
static_assert(std::is_same_v<decltype(std::move_if_noexcept(std::declval<SafeMove&>())),
                             SafeMove&&>);
```

Compiler-defaulted move constructors (`= default`) automatically compute `noexcept` from their members and bases. Hand-written move constructors and move assignment operators must spell `noexcept` explicitly.

## Implicit move on return from C++11 through C++23

When returning a named automatic variable or function parameter by value (`return local;`), compilers try copy elision first if permitted. When elision does not occur—for example, returning a function parameter or converting a local variable to another type—`[class.copy.elision]` performs **implicit move**: overload resolution runs a first pass treating the returned local or parameter as an rvalue, falling back to an lvalue only if no viable rvalue match exists.

C++23 (P2266R3) simplified these rules cleanly around **move-eligible** expressions in `return`, `co_return`, and `throw`. Previously, implicit move only applied to constructors returning the exact type or compatible types under awkward special-case wording, failing on user-defined rvalue conversion operators or returning rvalue references:

```cpp
struct Output {};
struct Builder {
    operator Output() && { return Output{}; }
    operator Output() const& = delete;
};

Output finalize(Builder b) {
    return b; // Compiles in C++23 (P2266R3); failed in C++20
}
```

> **Standardese.** Under `[class.copy.elision]`, an id-expression naming an automatic variable or parameter in a `return` or `throw` statement is move-eligible, so overload resolution treats it as an rvalue first without needing `std::move`.

## What to remember

- `std::move` casts an lvalue to an xvalue (`T&&`) at compile time; calling it on a `const` object produces `const T&&` and silently copies.
- Any user-declared destructor or copy operation suppresses implicit move generation; any user-declared move operation deletes implicit copy operations.
- Always mark non-throwing move constructors and move assignment operators `noexcept` so `std::move_if_noexcept` lets containers move instead of copy during reallocation.
- Leave moved-from objects valid, destructible, and self-move safe using `std::exchange`, and omit `std::move` on `return local;` so NRVO and C++23 implicit move both work cleanly.

## Concept Map Outline

- **Copy and move semantics:** Move semantics transfers ownership from expiring objects while respecting constness and exception safety.
  - **std::move and constness:** std::move only casts to an rvalue reference and yields to copy semantics on const objects.
    - **Unconditional rvalue cast:** std::move produces an xvalue at compile time without emitting runtime instructions.
    - **const T&& fallback:** Applying std::move to a const variable creates const T&&, which calls the copy constructor.
  - **Special member generation:** User-declared destructors, copies, or moves alter which special members the compiler generates.
    - **Destructor suppresses move:** Declaring any destructor disables implicit move generation and falls back to copying.
    - **Move deletes copy:** Declaring a custom move operation implicitly deletes copy construction and copy assignment.
    - **Rule of Zero vs Five:** Compose RAII wrappers to avoid custom members, or explicitly define all five for raw handles.
  - **Safe move implementation:** Custom move operations must clear the source, survive self-assignment, and preserve invariants.
    - **std::exchange:** Atomically steals a pointer or handle value while resetting the source member to null.
    - **Self-move guard:** Checking this == &other prevents freeing your own buffer during a = std::move(a).
    - **Valid unspecified state:** Moved-from standard objects remain destructible and assignable without guaranteeing emptiness.
  - **noexcept and containers:** Containers use std::move_if_noexcept to preserve strong exception safety during reallocation.
    - **std::move_if_noexcept:** Selects rvalue move only if the move constructor is noexcept or copying is unavailable.
    - **Explicit noexcept required:** User-written move operations do not infer noexcept automatically and must annotate it.
  - **Implicit move on return:** Returning a local variable or parameter automatically attempts rvalue overload resolution first.
    - **C++23 P2266R3 rules:** Simpler implicit move treats move-eligible id-expressions uniformly as rvalues across conversions.

## Standardese Quiz Questions

### Question 1 [warmup] ([utility.move])

What does `std::move(x)` actually do at runtime when executed on a local `std::vector<int> x`?

```cpp
std::vector<int> a{1, 2, 3};
auto b = std::move(a);
```

A. std::move copies the heap pointer and zeroes a inside the std::move function body
B. std::move emits zero instructions; it simply casts a to an xvalue so vector's move constructor is selected
C. std::move immediately invokes a.~vector() after returning
D. std::move swaps the stack frames of a and b

**Answer (B):** std::move emits zero instructions; it simply casts a to an xvalue so vector's move constructor is selected

**Why:** std::move is a pure compile-time cast to std::remove_reference_t<T>&& ([utility.move]). The actual pointer transfer and zeroing happen inside std::vector's move constructor because overload resolution picks vector(vector&&) for the xvalue.

### Question 2 [warmup] ([utility.move], [dcl.init.ref])

What happens when you initialize `b` using `const std::string a = "hello"; std::string b = std::move(a);`?

```cpp
const std::string a = "hello";
std::string b = std::move(a);
```

A. Compilation fails because you cannot pass a const object to std::move
B. std::string's move constructor runs and clears a
C. std::string's copy constructor runs because std::move(a) has type const std::string&&
D. Undefined behavior from modifying a const object

**Answer (C):** std::string's copy constructor runs because std::move(a) has type const std::string&&

**Why:** std::move(a) preserves constness and returns const std::string&&. Because std::string(std::string&&) requires a non-const rvalue reference, overload resolution selects std::string(const std::string&) and copies a.

### Question 3 [tricky] ([utility.move.if.noexcept], [vector.modifiers])

Why does `std::vector<Item>::push_back` copy existing `Item` elements during reallocation when `Item` declares both `Item(const Item&)` and `Item(Item&&)` without `noexcept`?

```cpp
struct Item {
    Item(const Item&);
    Item(Item&&); // not noexcept
};
```

A. std::vector never moves elements during reallocation; it always copies
B. std::vector uses std::move_if_noexcept, which falls back to copying so the old buffer stays intact if moving throws mid-reallocation
C. Non-noexcept move constructors are treated as deleted by std::allocator
D. Because Item lacks a user-declared destructor, its move constructor is suppressed

**Answer (B):** std::vector uses std::move_if_noexcept, which falls back to copying so the old buffer stays intact if moving throws mid-reallocation

**Why:** To preserve push_back's strong exception guarantee, std::vector calls std::move_if_noexcept ([utility.move.if.noexcept]). Because Item has a copy constructor and its move constructor is not noexcept, move_if_noexcept yields const Item& and copies safely.

### Question 4 [tricky] ([class.copy.ctor], [class.copy.assign])

What is the effect of adding `~Widget() = default;` to a struct that has a `std::string` member and no explicitly declared copy or move functions?

```cpp
struct Widget {
    std::string name;
    ~Widget() = default;
};
```

A. Both copy and move operations remain implicitly defaulted as before
B. Copy operations are deleted while move operations remain defaulted
C. Move constructor and move assignment are implicitly deleted
D. Implicit move constructor and move assignment are not declared (suppressed), so moving Widget silently calls its copy operations

**Answer (D):** Implicit move constructor and move assignment are not declared (suppressed), so moving Widget silently calls its copy operations

**Why:** Under [class.copy.ctor] and [class.copy.assign], any user-declared destructor suppresses implicit declaration of both the move constructor and move assignment operator. Implicit copy operations remain declared, so moves quietly degrade into copies.

### Question 5 [standardese] ([lib.types.movedfrom])

What does the C++ standard guarantee about a moved-from `std::string s` after `auto t = std::move(s);`?

A. s is in a valid but unspecified state: it can be safely destroyed or reassigned, though its contents and length are unspecified
B. s is guaranteed to have s.empty() == true and s.capacity() == 0
C. Using s in any way—including destruction—is undefined behavior
D. s retains its original characters until s goes out of scope

**Answer (A):** s is in a valid but unspecified state: it can be safely destroyed or reassigned, though its contents and length are unspecified

**Why:** [lib.types.movedfrom] specifies that moved-from standard library objects are placed in a valid but unspecified state unless explicitly specified otherwise. Calling clear() or assigning a new value is safe; assuming empty() is not.

### Question 6 [standardese] ([class.copy.elision])

Why does `Output finalize(Builder b) { return b; }` compile in C++23 when `Builder` defines only `operator Output() &&` and deletes `operator Output() const&`?

```cpp
struct Output {};
struct Builder {
    operator Output() && { return {}; }
    operator Output() const& = delete;
};
Output finalize(Builder b) { return b; }
```

A. NRVO eliminates the conversion operator entirely for function parameters
B. C++23 P2266R3 classifies b in return b as move-eligible, so overload resolution treats b as an rvalue during implicit move
C. Parameters passed by value are always prvalues inside the function body
D. Because operator Output() const& is deleted, the compiler calls reinterpret_cast

**Answer (B):** C++23 P2266R3 classifies b in return b as move-eligible, so overload resolution treats b as an rvalue during implicit move

**Why:** Under C++23 [class.copy.elision] (P2266R3), an id-expression naming an automatic variable or parameter in a return statement is move-eligible, triggering an rvalue-first overload lookup that picks operator Output() && without needing std::move(b).
