Why does std::vector copy C++ elements during reallocation when their move constructor is not declared noexcept?
answer
- a promise about failed insertion
- half-moved old storage
- std::move_if_noexcept
- copyable or nothrow-movable
basics
~20 spush_back promises that a failed insertion at the end leaves the vector unchanged. A move that throws halfway would already have damaged old elements, so reallocation uses std::move_if_noexcept and copies unless the move is noexcept or the type cannot be copied.
solid answer
~40 sThe standard says that if an exception is thrown while inserting a single element at the end and `T` is copy-insertable or `is_nothrow_move_constructible_v<T>` is true, there are no effects. Reallocation builds the new storage element by element; if the fifth move throws, four old elements are already moved-from, so the original cannot be restored. Copying leaves the originals intact, so implementations relocate through `std::move_if_noexcept`, which yields `const T&` when the move may throw and `T` is copyable. For a `Buffer` that owns a heap array this means one allocation and copy per element on every growth. The fix is to declare the move constructor `noexcept` and guard it with `static_assert(std::is_nothrow_move_constructible_v<Buffer>)`. A move-only type is moved anyway and loses the no-effects promise.
code
cpp · 30 lines#include <cstddef>
#include <cstdio>
#include <vector>
template <bool NoThrowMove>
struct Buffer {
static inline int copies = 0, moves = 0;
std::size_t size = 0;
float* data = nullptr;
explicit Buffer(std::size_t n) : size(n), data(new float[n]{}) {}
Buffer(const Buffer& o) : size(o.size), data(new float[o.size]{}) { ++copies; }
Buffer(Buffer&& o) noexcept(NoThrowMove) : size(o.size), data(o.data) {
o.size = 0;
o.data = nullptr;
++moves;
}
~Buffer() { delete[] data; }
};
template <bool B>
void load_level(const char* label) {
std::vector<Buffer<B>> level;
for (int i = 0; i < 100; ++i) level.emplace_back(1024);
std::printf("%s copies=%d moves=%d\n", label, Buffer<B>::copies, Buffer<B>::moves);
}
int main() {
load_level<false>("move may throw:");
load_level<true>("move is noexcept:");
}go deeper
Remember that a move constructor without noexcept makes std::vector copy elements when it grows, and that adding noexcept fixes it.
Explain the no-effects promise for insertion at the end, why a half-finished move cannot be undone, and how move_if_noexcept picks const T& or T&&.
Track down hidden copies in a growth-heavy loop with a profiler or counters, and keep them out with a static_assert on is_nothrow_move_constructible_v.
Make nothrow moves a checked property of resource types in shared code, since one throwing member silently turns every container growth into deep copies.
## The promise `std::vector` made For `push_back` and `emplace_back`, the standard's wording in the vector modifiers section reads: if an exception is thrown while inserting a single element at the end and `T` is *Cpp17CopyInsertable* or `is_nothrow_move_constructible_v<T>` is `true`, **there are no effects**. Otherwise, if an exception is thrown by the move constructor of a non-copy-insertable `T`, the effects are unspecified. `reserve` carries the same rule. This is the "strong" exception guarantee, and keeping it is what forces the copy. ## Why a throwing move breaks it When the vector is full, inserting one more element means: 1. allocate a larger block; 2. construct each existing element in the new block from the old one; 3. construct the new element; 4. destroy the old elements and free the old block. If step 2 **copies**, a throw at element *k* is harmless: destroy the *k* new copies, free the new block, and the old elements are untouched. If step 2 **moves** and the move at element *k* throws, elements 0 to *k-1* in the old block are already moved-from; moving them back could throw again, so the original state cannot be guaranteed. A move that is declared `noexcept` cannot throw, so moving is safe. ## `std::move_if_noexcept`: the decision in one return type `<utility>` declares: ```cpp template<class T> constexpr conditional_t< !is_nothrow_move_constructible_v<T> && is_copy_constructible_v<T>, const T&, T&&> move_if_noexcept(T& x) noexcept; ``` | Move constructor | Copy constructor | Result type | Reallocation does | |---|---|---|---| | `noexcept` | any | `T&&` | moves | | may throw | available | `const T&` | copies | | may throw | deleted | `T&&` | moves, and loses the no-effects promise | | not declared (copy only) | available | either | copies, since `T&&` binds to the copy constructor | libc++ relocates through `std::move_if_noexcept(*__iter)` in its `__uninitialized_allocator_relocate`; libstdc++ uses `__uninitialized_move_if_noexcept_a`. Both are implementation details that put the standard's rule into code. ## Seeing it happen The example builds 100 `Buffer`s with `emplace_back` and counts constructor calls. With libc++ and a move constructor that may throw, it prints `copies=127 moves=0`; with `noexcept`, `copies=0 moves=127`. The total, 1+2+4+...+64, comes from libc++ doubling its capacity, which is that library's growth policy and not something the standard fixes. For a `Buffer` holding a 1024-float array, every one of those copies is a heap allocation and a 4 KB `memcpy` during level loading. ## Fixing and guarding it - Declare the move constructor `noexcept` when it only transfers pointers and integers. - Add `static_assert(std::is_nothrow_move_constructible_v<Buffer>);` next to the class, so a later member with a throwing move breaks the build instead of silently slowing it down. - In a class template, use a conditional specifier such as `noexcept(std::is_nothrow_move_constructible_v<T>)`. - Note that growth looks only at **move construction**; `noexcept` on move assignment matters for other operations such as `std::swap`, not for reallocation. - If the compiler stopped declaring the move constructor at all (for instance because the class declares a destructor), `std::vector` copies for that reason instead; those generation rules are covered with the rule of zero, three and five. ## Diagnosing it in a real loader The symptom is usually a frame spike or slow level load with the copy constructor of a resource type high in a profile, called from inside `emplace_back` or `push_back`. To confirm the cause: 1. Check `std::is_nothrow_move_constructible_v<Buffer>` in a `static_assert`; if it fails, the move constructor is either missing or not `noexcept`. 2. If it is missing, find what suppressed it (a declared destructor or copy operation); if it is present, add `noexcept`. 3. Re-measure: the copies should disappear, and the total number of moves equals the number of elements relocated. Calling `reserve` with the final count also removes the relocations, but that only hides the problem for one call site, and only when the count is known up front; the `noexcept` fix applies to every container and every growth. ## Implementation extras libc++ built without exceptions moves unconditionally in that same function, since nothing can throw, and relocates types it knows to be trivially relocatable with `memcpy`. These are libc++ choices; the standard only specifies the guarantee.
- Does noexcept on the move assignment operator change what std::vector does when it grows?No. Reallocation constructs elements in new storage, so only the move constructor is consulted, through `is_nothrow_move_constructible_v<T>`. A `noexcept` move assignment still matters elsewhere, for example to `std::swap`'s own `noexcept` specification, but it does not stop the copies on growth.
- What happens if a move-only element's move constructor throws during reallocation?The vector moves such elements anyway, because there is no copy to fall back on. The standard then says the effects are unspecified: some old elements may already be moved-from. The program keeps running with a valid vector, but the no-effects promise is gone, which is why move-only types should still have `noexcept` moves.
- std::vector always moves elements on growth if the type has any move constructor.
- noexcept on the move assignment operator is what vector checks when it reallocates.
- A move-only type cannot be stored in std::vector unless its move is noexcept.
- noexcept is only documentation; the compiler and library ignore it.
- Turning on optimisation makes vector use the throwing move constructor instead of the copy.