skip to content

Move Semantics

Rvalue references let an object hand over its resources instead of copying them, and std::move is only a cast. Middle-level interviews test exactly when a copy becomes a move.

on this pageshow

explore

questions

20

In C++, does returning a large Report object by value from make_report() copy it, or should you fill an out-parameter instead?

level: juniorimportance: must knowfreq 62%

answer

  1. where the result object lives
  2. a prvalue versus a named local
  3. the fallback is a move
  4. out-parameters for reused capacity

basics

~10 s

Return by value. Since C++17 a returned prvalue is built straight in the caller's object, a returned named local usually is too (NRVO), and otherwise a movable local is moved, not copied.

solid answer

~50 s

Write `Report make_report()` and `auto r = make_report();`. If the function ends in `return Report{...};`, C++17 guarantees there is no temporary and no copy or move: the return statement initializes `r` directly. If it builds a named local and returns it, compilers normally apply named return value optimisation (NRVO) and construct the local in `r`'s storage; that is permitted, not required. When NRVO does not happen, a returned local is treated as an rvalue, so `Report`'s move constructor runs, which for a type holding a `std::vector` is a few pointer copies. An out-parameter (`void make_report(Report& out)`) forces the caller to construct an object first and hides the data flow, so return by value is the default. The real exceptions are types whose move is as expensive as a copy, and loops that want to reuse an existing buffer's capacity.

go deeper

for a junior

Say that returning by value is the default in modern C++: the result is built in the caller's object or moved, not copied, and out-parameters are rarely needed for speed.

for a middle

Separate the guaranteed C++17 elision of a returned prvalue from NRVO for a named local, and name the implicit move as the fallback.

for a senior

Identify the real costs: types without a cheap move, returns that are not a plain name, and loops that should reuse a caller's buffer capacity.

for a principal

Set the API rule: return results by value, keep out-parameters for deliberate buffer reuse, and flag std::move on returns in review.

## Where the returned object ends up A function with a class return type, such as `Report make_report()`, produces its value in the caller's **result object**. In `auto r = make_report();` that result object is `r` itself. The `return` statement initializes it by **copy-initialization** from the operand, and the question "does it copy?" is really "how many objects does that initialization create?". ## The three outcomes of `return` | Operand of `return` | What C++ does | Cost | |---|---|---| | a prvalue: `return Report{2024};` | since C++17 the prvalue initializes `r` directly | no copy, no move, guaranteed | | a named local: `Report rep; ...; return rep;` | **NRVO**: the local may be constructed in `r`'s storage | usually nothing; permitted, not required | | a named local when NRVO does not apply | the name is treated as an rvalue (**implicit move**) | one move; a copy if the local is `const` or the type has no move constructor | | anything else, such as a member or a global | ordinary copy-initialization from an lvalue | a copy | Before C++17 the first row was also only a permission, and the code still needed an accessible copy or move constructor. Since C++17 a prvalue is not a temporary waiting to be copied; it is a recipe that runs directly in the destination. ## Why out-parameters stopped being the fast path - **They double the work for the caller.** `Report out; make_report(out);` default-constructs a `Report`, then overwrites it. - **They need a default constructor** and a mutable object, so the result cannot be `const` and the type cannot insist on being fully initialized. - **They hide the data flow.** A reader must check the signature to learn which arguments are inputs. - **The saving is gone.** With elision and moves, returning a `Report` that holds `std::vector<Row>` costs at most a few pointer copies. ## When returning by value does cost something 1. The type's move is as expensive as its copy: a `std::array<double, 4096>` or a struct of fixed arrays has no heap pointer to steal, so if elision fails, the whole array is copied. 2. The return expression is not a plain name or prvalue: `return cond ? a : b;` or `return this->cache_;` copies. 3. The function is a hot loop's producer and the caller wants to **reuse capacity**: `std::getline(in, line)` writes into an existing `std::string`, keeping its allocation across thousands of lines, which return-by-value cannot do. The third case is the honest argument for an out-parameter, and it is about reusing an allocation, not about avoiding a copy. ## Reading a factory with these rules Take a `make_report()` that loads rows from a database and returns a `Report` holding a `std::vector<Row>` of a million rows and a `std::string` title. Walk through what each style costs the caller: - `return Report{load_rows(), title};` builds the `Report` once, in the caller's variable; the vector and string are moved into its members by its constructor, which is pointer work. - `Report rep; rep.rows = load_rows(); return rep;` builds `rep` in the caller's variable under NRVO; without NRVO it moves once. - `void make_report(Report& out)` makes the caller create an empty `Report` first, then assigns into it: one extra construction and one move assignment per member. None of the three copies a million rows. The differences are a handful of pointer operations, which is why readability decides between them. The first form is the easiest to read and the only one that also works for a `Report` that cannot be moved at all. ## Optimisation level is not the deciding factor Guaranteed elision is a language rule, so it happens in every build. NRVO is technically an optimisation, but Clang applies it without `-O`: a `Report` returned by name from a function compiled at `-O0` still prints no copy and no move. The case that changes behaviour is the flag `-fno-elide-constructors`, which disables NRVO but cannot disable the guaranteed C++17 elision. ## The rule of thumb - Return by value; prefer returning a prvalue or a single named local. - Do not wrap the return in `std::move`; it blocks NRVO. - Use an out-parameter only to reuse a caller-owned buffer across calls, and say so in the function's name or comment.

  • Does make_report() returning a prvalue need Report to have a move constructor in C++17?
    No. Since C++17 a prvalue of the same type initializes the result object directly, so no copy or move constructor is called or even required to exist. A `Report` holding a `std::mutex` can be returned this way. Returning a named local is different: NRVO is optional, so that form still needs an accessible copy or move constructor.
  • Why can std::getline(in, line) be faster than a function returning std::string in a loop?
    Because the caller's `line` keeps its allocation between calls. Each `getline` erases and refills the same buffer, so after the first long line no further allocations happen. A function returning a fresh `std::string` must allocate a new buffer per call for long lines, even though the return itself is elided or moved.

  • Returning a large object by value always copies it, so out-parameters are faster.
  • Copy elision only happens with optimisation enabled, so debug builds copy every return.
  • C++17 guarantees NRVO for any function that returns a single named local.
  • Adding std::move to the return statement is how you avoid the copy.
  • Returning by value is fine only if the type has a cheap copy constructor.

Assumes C++17 or later, where returning a prvalue is guaranteed not to copy or move; in C++11 and C++14 that elision was only permitted.

open as a page

In C++, after std::string b = std::move(a); runs, what state is a left in, and what can you still do with it?

level: juniorimportance: must knowfreq 70%

basics

~20 s

A moved-from std::string is in a valid but unspecified state: you may destroy it, assign to it, clear it or ask its size, but must not rely on its value, not even on it being empty.

open as a page

In C++, what does std::move actually do to the object you pass to it?

level: juniorimportance: must knowfreq 85%

basics

~20 s

std::move moves nothing: it is a cast that returns its argument as an xvalue, static_cast to an rvalue reference. A move happens only if that xvalue then selects a move constructor or move assignment operator, which transfers the resources.

open as a page

In C++17, what separates return Report{}; from returning a named local Report, and which of the two elisions is guaranteed?

level: middleimportance: must knowfreq 60%

basics

~20 s

return Report{}; returns a prvalue, and C++17 guarantees it initializes the caller's object directly with no copy or move. Returning a named local relies on NRVO, which compilers may apply but need not; without it the local is moved.

open as a page

In C++, when is a parameter declared T&& a forwarding reference rather than an ordinary rvalue reference?

level: middleimportance: must knowfreq 65%

basics

~20 s

T&& is a forwarding reference only when T belongs to that function template, is deduced from the call, and the parameter is exactly T&& with no const; auto&& behaves alike. const T&&, std::vector<T>&& and a class template's T&& are rvalue references.

open as a page

For a C++ Buffer class that owns a heap array, how do you write its move constructor and move assignment operator?

level: middleimportance: must knowfreq 68%

basics

~20 s

The move constructor copies the source's pointer and size, then sets the source to nullptr and 0 so its destructor frees nothing. Move assignment also frees its own array first and survives self-move. Both are noexcept.

open as a page

Why does std::vector copy C++ elements during reallocation when their move constructor is not declared noexcept?

level: middleimportance: must knowfreq 66%

basics

~20 s

push_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.

open as a page

In C++, given overloads f(const std::string&) and f(std::string&&), which one does each kind of argument select, and why?

level: middleimportance: must knowfreq 65%

basics

~20 s

An lvalue can bind only to const std::string&, so it selects that overload. An rvalue - a prvalue like make() or an xvalue like std::move(s) - can bind to both, and overload resolution prefers std::string&&. A const rvalue falls back to const std::string&.

open as a page

Why does return std::move(local); in a C++ function returning by value make it slower, and when is std::move on return still right?

level: seniorimportance: must knowfreq 55%

basics

~20 s

NRVO needs the return operand to be the plain name of a local. std::move(local) is a call, so the object cannot be built in the caller's storage and a move always runs. Keep std::move for subobjects such as members.

open as a page

In a C++ factory template<class T, class... Args> make_logger(Args&&... args), how do reference collapsing and std::forward<Args> preserve each argument's value category?

level: seniorimportance: must knowfreq 55%

basics

~20 s

For an lvalue argument Args is deduced as U&, so Args&& collapses to U& and std::forward<U&> returns an lvalue; for an rvalue Args is U, the parameter is U&&, and std::forward<U> returns an xvalue. The deduced type carries the category through.

open as a page

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%

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.

open as a page

In C++, when do you write std::forward<T>(x) and when std::move(x) to pass an argument on?

level: juniorimportance: should knowfreq 60%

basics

~20 s

std::move(x) always yields an rvalue: use it on objects you own and no longer need. std::forward<T>(x) yields an rvalue only if the caller passed one: use it only on a forwarding reference T&& x in a template.

open as a page

In a C++ Matrix operator+, why do return a; for a by-value parameter and return a += b; behave differently from returning a fresh local?

level: middleimportance: should knowfreq 50%

basics

~20 s

NRVO applies only to a named local, never a parameter, so return a; on a by-value parameter moves instead. return a += b; is not a name at all but an lvalue reference expression, so it copies.

open as a page

Which C++ standard library types promise a specific state after being moved from, and which promise only a valid but unspecified one?

level: middleimportance: should knowfreq 45%

basics

~10 s

unique_ptr, shared_ptr and weak_ptr become null, std::thread and unique_lock own nothing, and std::future becomes invalid. std::optional keeps has_value() unchanged. std::string, std::vector and std::function promise only a valid but unspecified state.

open as a page

In C++, what distinguishes an lvalue, an xvalue and a prvalue, and which category does std::move(s) produce?

level: middleimportance: should knowfreq 55%

basics

~20 s

Every C++ expression is exactly one of three: an lvalue names an object you keep using, an xvalue denotes an object whose resources may be reused, and a prvalue computes a value or initializes an object. std::move(s) is an xvalue.

open as a page

Since C++17, how can a C++ make_report() factory return a Report that holds a std::mutex, and when does it still fail to compile?

level: seniorimportance: should knowfreq 38%

basics

~20 s

Return a prvalue: return Report{n}; initializes the caller's object directly, so C++17 needs no copy or move constructor. Returning a named local still fails, because NRVO is optional and a usable copy or move constructor must exist.

open as a page

In C++, why does the perfect-forwarding factory call make_logger<Logger>({"core", 3}, flush_hook) fail to compile when a direct Logger constructor call with the same arguments works?

level: seniorimportance: should knowfreq 35%

basics

~20 s

A forwarding reference must deduce a type from each argument. A braced list has no type, and an overloaded function name like flush_hook names several functions, so deduction fails. The direct call works because the constructor's parameter types are already known.

open as a page

In C++, why does copying a non-const Logger call its template<class S> Logger(S&& name) constructor instead of the copy constructor, and how do you prevent it?

level: seniorimportance: should knowfreq 35%

basics

~20 s

For a non-const Logger lvalue, S deduces as Logger&, giving Logger(Logger&) - a better match than the copy constructor's const Logger&, which adds const. Non-templates win only exact ties. Constrain the template, for example to types std::string is constructible from.

open as a page

In C++, what must happen when an object is move-assigned to itself, as in level[i] = std::move(level[j]) with i == j?

level: seniorimportance: should knowfreq 38%

basics

~20 s

The object must end in a valid state, though its value may be lost. The standard library promises exactly that for its own types, and a hand-written move assignment needs a this != &other guard or must detach the source before freeing.

open as a page

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%

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.

open as a page