skip to content

In C++, why does v.push_back(std::move(cfg)) compile without complaint yet copy when cfg is a const std::string?

level: seniorimportance: should knowfreq 40%

answer

  1. the cast keeps const
  2. const T&& meets T&&
  3. const T& accepts everything
  4. const members, lambdas, range-for

basics

~10 s

std::move(cfg) produces a const std::string&& xvalue. push_back(std::string&&) cannot bind it, because that would drop const, so overload resolution falls back to push_back(const std::string&), which binds anything and copies. No error is required.

solid answer

~40 s

`std::move` casts to `remove_reference_t<T>&&`, and `remove_reference_t` keeps cv-qualifiers, so a `const std::string` argument becomes a `const std::string&&` xvalue. A move constructor or `push_back(T&&)` takes a non-const `std::string&&`, which cannot bind a const object - a move must modify its source. The other overload, `push_back(const std::string&)`, binds lvalues and rvalues alike, so it is viable and selected: the code compiles and copies. Clang with `-Wall -Wextra` does not warn. The same trap appears wherever `const` is implicit: inside a `const` member function, on a by-copy capture in a non-`mutable` lambda, in `for (const auto& x : v)`, and on a function returning `const T` by value. Fix it by removing the `const`, not by adding casts.

code

cpp · 24 lines
cpp
#include <iostream>
#include <string>
#include <utility>
#include <vector>

struct Name {
    std::string text;
    explicit Name(std::string t) : text(std::move(t)) {}
    Name(const Name& o) : text(o.text) { std::cout << "copy\n"; }
    Name(Name&& o) noexcept : text(std::move(o.text)) { std::cout << "move\n"; }
};

int main() {
    std::vector<Name> v;
    v.reserve(4);
    const Name fixed{"gamma"};
    Name loose{"delta"};
    v.push_back(std::move(fixed));   // const Name&& binds only to const Name&
    v.push_back(std::move(loose));   // Name&& selects the move constructor
    auto f = [cap = Name{"eps"}]() { return std::move(cap); };
    std::cout << "lambda: ";
    Name out = f();                  // capture is const in a non-mutable lambda
    (void)out;
}

go deeper

for a junior

Remember that a const object cannot be moved from: std::move compiles, but the copy constructor runs instead.

for a middle

Trace the types: std::move on a const std::string gives const std::string&&, which T&& cannot bind but const T& can.

for a senior

Find the hidden const - const member functions, non-mutable lambdas, const auto& loops, const return types - and prove the copy with an instrumented type.

for a principal

Decide how the team catches this class of silent copies: review rules on const locals that are moved, static analysis, and allocation budgets in hot paths.

## What the cast produces for a const argument The standard specifies `std::move(t)` as `static_cast<remove_reference_t<T>&&>(t)`. For a `const std::string cfg`, `T` is deduced as `const std::string&`, `remove_reference_t<T>` is `const std::string`, and the result is a **`const std::string&&` xvalue**. The cast strips the reference, never the `const`. That type is legal but almost useless: an rvalue reference to const says "you may treat this as expiring" and "you may not modify it" at once. Moving *is* modification - a move constructor takes over the source's buffer and must leave the source changed. ## Why the copy constructor wins Overload resolution for `v.push_back(std::move(cfg))` with `std::vector<std::string> v` runs in two steps: 1. **Viability.** `push_back(std::string&&)` needs to bind a non-const rvalue reference to a const object. Reference binding may add `const`, never remove it, so this overload is not viable. `push_back(const std::string&)` can bind any `std::string` expression, so it is viable. 2. **Selection.** Only one candidate survives, so it is chosen, and it copies the string into the vector. Nothing here is ill-formed, so the compiler has no reason to complain. Clang 21 with `-Wall -Wextra` compiles the code example for this question without a warning. The fallback is by design: a move is an optimization of a copy, and a type that cannot be moved from is copied. ## Where const sneaks in The explicit `const std::string cfg` is easy to spot. These are not: - **A `const` member function.** Inside `Name take() const { return std::move(n_); }` the member `n_` is accessed through a pointer to const, so `std::move(n_)` is a `const` xvalue and the return copies. - **A non-`mutable` lambda.** By-copy captures are `const` inside the closure's call operator, so `[local] { return std::move(local); }` copies; adding `mutable` makes it move. - **A range-for over `const auto&`.** `for (const auto& x : src) dst.push_back(std::move(x));` copies every element. Use `auto&` or move the whole container. - **A function returning `const T` by value.** Initializing a new variable from it is unaffected because the prvalue initializes the object directly, but `v.push_back(make_const())` binds a const temporary and copies. - **A `const` local kept for "safety".** A local declared `const` and moved at the end of scope copies at exactly the point the author meant to save a copy. ## Detecting it - **An instrumented type** whose copy and move constructors print or count, as in the code example, shows the copy immediately. - **A `static_assert`** next to the move documents the intent: `static_assert(!std::is_const_v<std::remove_reference_t<decltype(cfg)>>);`. - **Profiling and allocation counters** catch it in hot paths, where an unexpected heap allocation per call is the usual symptom. - **Static analysis checks** for moving const arguments exist in common tooling; the compiler's default warning set does not include one. ## Fixing it | Situation | Fix | |---|---| | `const` local moved at the end | drop the `const` from the declaration | | `const` member function moving a member | make the function non-const, or ref-qualify it with `&&` | | non-`mutable` lambda moving a capture | add `mutable` | | range-for with `const auto&` | iterate with `auto&`, or move the container itself | | function returning `const T` | return plain `T` | A `const_cast` that strips `const` before the move would compile, but it is undefined behaviour if the object was originally defined `const`, and it defeats the purpose of having declared it `const` in the first place. The honest fix is always to stop declaring as `const` an object you intend to give away. ## Why it matters in practice For a short `std::string` that fits in the library's small-string buffer (libc++ and libstdc++ both have one, as an implementation choice), the copy and the move cost about the same, so the bug is invisible in a quick test. It shows up with large payloads: a vector of meshes, a long JSON document, a `std::vector<std::byte>` network buffer. There the "move" that is really a copy means: 1. a heap allocation the author believed was gone, 2. a full copy of the payload, proportional to its size, 3. a source object that still holds its data, so memory peaks at twice the payload until the source dies. The symptom in a profiler is an allocation and a `memcpy`-like loop at a line that reads `std::move`. Because the line looks correct, reviewers skip it, which is why the habit of asking "is the source const?" at every `std::move` pays off.

  • Why does the standard not make std::move on a const object ill-formed?
    `const T&&` is a valid type, and generic code often calls `std::move` on objects whose constness depends on a template argument. Rejecting it would break that code, while falling back to the copy keeps it correct, only slower. The move is treated as an optimization of the copy, so a type or object that cannot be moved from is copied.
  • Why does the non-mutable lambda in the example copy while a mutable one moves?
    A lambda's call operator is `const` unless the lambda is declared `mutable`, so inside it every by-copy capture is accessed as a const member. `std::move(loose)` then yields a `const Name&&` that only the copy constructor accepts. With `mutable`, the call operator is non-const, the capture is a non-const member, and the move constructor is selected.

  • std::move removes const from its argument.
  • Moving from a const object is a compile error.
  • The compiler warns by default whenever std::move on a const object copies.
  • A const_cast before std::move is the clean fix.
  • A by-copy lambda capture can always be moved out of the lambda.