skip to content

A code review asks why void Registry::add(std::string&& name) { names_.push_back(name); } still copies the string — what is the answer?

level: seniorimportance: must knowfreq 60%

answer

  1. declared type is not category
  2. a name can be used twice
  3. named rvalue references are lvalues
  4. cast again at the last use

basics

~10 s

Inside add, the expression name is an lvalue because it is a name, even though its declared type is std::string&&. So push_back(name) selects push_back(const std::string&) and copies; push_back(std::move(name)) restores the rvalue and moves.

solid answer

~40 s

A variable's declared type and the value category of an expression naming it are separate things. The `std::string&&` parameter only restricts what the *caller* may pass - rvalues - but inside the body `name` is an identifier for a variable, and the standard treats named rvalue references as lvalues. `names_.push_back(name)` therefore binds to `push_back(const std::string&)` and copies. The rule is deliberate: a name can be read many times, and if every use were an rvalue, the first call could empty the string before the second. The fix is `names_.push_back(std::move(name));` at the **last** use. One exception is built in: `return name;` moves implicitly, because since C++20 an rvalue reference parameter is an implicitly movable entity, and since C++23 such a return operand is an xvalue.

code

cpp · 26 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"; }
};

struct Registry {
    std::vector<Name> names;
    void add_named(Name&& n) { names.push_back(n); }            // n is an lvalue here
    void add_moved(Name&& n) { names.push_back(std::move(n)); } // cast back to an xvalue
};

int main() {
    Registry r;
    r.names.reserve(4);
    std::cout << "add_named:\n";
    r.add_named(Name{"alpha"});
    std::cout << "add_moved:\n";
    r.add_moved(Name{"beta"});
}

go deeper

for a junior

Remember the slogan: naming a variable gives an lvalue, whatever its declared type, so a std::string&& parameter needs std::move again to be moved from.

for a middle

Separate declared type from expression category, and explain why push_back(const T&) is the overload that can bind the named parameter.

for a senior

Place std::move at the last use only, explain the use-twice hazard the rule prevents, and know the return-statement exception and its C++20 and C++23 history.

for a principal

Turn this into a review checklist item: every concrete T&& parameter should be moved exactly once, and an instrumented type proves it.

## Declared type versus expression category The reviewer's surprise comes from mixing up two properties: - The **declared type** of `name` is `std::string&&`, an rvalue reference. That governs **binding**: only an rvalue argument - a temporary or a `std::move` result - can initialize the parameter. A caller who writes `reg.add(s)` with a named `s` gets a compile error. - The **value category** of the expression `name` inside the body is **lvalue**. Per the draft, an unqualified id-expression naming a variable is an lvalue unless it is move-eligible (see below). The draft's note on value categories sums it up: named rvalue references are treated as lvalues, and unnamed rvalue references to objects as xvalues. So `names_.push_back(name)` asks `std::vector<std::string>::push_back` to accept an lvalue. Of its two overloads, `push_back(const T&)` and `push_back(T&&)`, only the first can bind an lvalue, and it copies. ## Why the language makes the name an lvalue The rule protects the function body from itself. Consider: ```cpp void Registry::add(std::string&& name) { index_.insert(name); // first use names_.push_back(name); // second use } ``` If `name` were an rvalue at every use, the first line could move the characters out and the second would store an empty string - with no `std::move` anywhere to warn the reader. Making names lvalues means a move from a named object is always **spelled out**, and the programmer places it where the object is no longer needed. ## The fix, and where to put std::move 1. Identify the **last** use of the parameter in each control-flow path. 2. Wrap that use, and only that use, in `std::move`: `names_.push_back(std::move(name));`. 3. Do not touch `name` afterwards except to assign it or destroy it; its value is now valid but unspecified. 4. If the function needs the value twice, copy at the first use and move at the last. `std::move` here is correct and `std::forward` is not: `name` is not a forwarding reference, it is a plain rvalue reference with a known type, so an unconditional cast is what is wanted. ## The return-statement exception There is one place where the language moves from a name on its own: the operand of `return`, `co_return` or a throw-expression, when it names a local object or parameter. The rules for that have changed across standards: | Standard | `return name;` where `name` is a `std::string&&` parameter | |---|---| | C++11 to C++17 | the rule only covered objects, not rvalue references | | C++20 | an rvalue reference to a non-volatile object is an implicitly movable entity, so the return moves | | C++23 | the move-eligible id-expression is itself an **xvalue** | Clang already moves in this case in `-std=c++17` mode as well. The details, and why `return std::move(local)` can hurt, belong to the material on copy elision; for this review, the point is that `push_back(name)` is not a return statement and gets no such help. ## Spotting the pattern in review - A parameter declared `T&&` (with a concrete `T`, not a template parameter) that is used without `std::move` anywhere is almost always a missed move. - A `std::move(name)` followed by another read of `name` is a use of a moved-from value. - An instrumented type that prints from its copy and move constructors, as in the code example for this question, settles the argument in a minute. - A by-value parameter, `void add(std::string name)`, accepts both lvalues and rvalues and still needs `std::move(name)` inside for the same reason: `name` is a name. ## The same rule one level down The rule applies to every name, not only to parameters, and it composes: - A **local** declared `std::string&& tmp = make();` is an lvalue when named, exactly like the parameter. - A **data member** reached through a named object, `msg.body`, is an lvalue; `std::move(msg).body` is an xvalue, which is how a function can move one member out of an object it owns. - A **structured binding** names an lvalue too, whatever the type of the object it refers to. - Passing `name` on to a helper that itself takes `std::string&&` fails to compile, which is often how the copy is discovered: the copying overload of `push_back` merely hid the same mistake. The one-sentence answer for the reviewer: the parameter's type says what callers may pass; the parameter's name is an lvalue, so the body must cast it again to move it.

  • Would declaring the parameter as std::string name, by value, remove the need for std::move inside add?
    No. A by-value parameter is still a named variable, so `name` is still an lvalue inside the body and `push_back(name)` still copies. The by-value form changes what callers may pass - lvalues are copied in, rvalues moved in - but the body must still write `push_back(std::move(name))` to move from its own copy.
  • Why is std::forward the wrong tool for this parameter?
    `std::forward<T>` preserves a category that was deduced into a template parameter. Here the parameter type is the concrete `std::string&&`, so there is nothing to preserve: the caller always passed an rvalue. `std::move` states the intent directly. `std::forward<std::string>(name)` would happen to produce the same xvalue, but it misleads the next reader into looking for a template.
  • In C++20 and later, what does return name; do when name is a std::string&& parameter of a function returning std::string?
    It moves. Since C++20 an rvalue reference to a non-volatile object with automatic storage is an implicitly movable entity, so the returned id-expression is treated as an rvalue and the move constructor runs. C++23 goes further and classifies it as an xvalue outright. Earlier standards copied here.

  • A parameter declared std::string&& is an rvalue everywhere in the function body.
  • push_back(name) moves because the parameter's type is an rvalue reference.
  • Use std::forward on a std::string&& parameter to move it.
  • Calling std::move on the parameter at its first use is always safe.
  • Taking the parameter by value means no std::move is needed inside.

Assumes C++23; implicit move of a returned rvalue reference parameter arrived in C++20, and C++23 made such a return operand an xvalue.