skip to content

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%

answer

  1. NRVO excludes parameters
  2. a returned name is treated as an rvalue
  3. operator+= returns an lvalue reference
  4. two locals, one result slot

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.

solid answer

~50 s

NRVO lets the compiler build a returned local directly in the result object, but only for the plain name of a non-volatile automatic object that is not a parameter. A by-value parameter is constructed by the caller before the function starts, so it cannot also be the result object. What saves `return a;` is **implicit move**: a returned name of a local or parameter is first treated as an rvalue, so `Matrix`'s move constructor runs. `return a += b;` gets neither: the operand is a call to `operator+=`, which returns `Matrix&`, an lvalue, so the result is copy-constructed. Measured with Clang: building a local `r` from `a` costs one copy and nothing on return; the parameter form costs a copy in and a move out; the `+=` form costs two copies. Two locals returned on different paths, `return c ? x : y;` and a returned member also lose NRVO.

code

cpp · 25 lines
cpp
#include <cstdio>
#include <utility>
#include <vector>

struct Matrix {
    std::vector<double> cells;
    explicit Matrix(std::size_t n) : cells(n * n) {}
    Matrix(const Matrix& o) : cells(o.cells) { std::puts("  copy"); }
    Matrix(Matrix&& o) noexcept : cells(std::move(o.cells)) { std::puts("  move"); }
    Matrix& operator+=(const Matrix& o) {
        for (std::size_t i = 0; i < cells.size(); ++i) cells[i] += o.cells[i];
        return *this;
    }
};

Matrix add_named(const Matrix& a, const Matrix& b) { Matrix r = a; r += b; return r; }
Matrix add_param(Matrix a, const Matrix& b) { a += b; return a; }
Matrix add_chain(Matrix a, const Matrix& b) { return a += b; }

int main() {
    Matrix x(512), y(512);
    std::puts("named:"); Matrix s1 = add_named(x, y);
    std::puts("param:"); Matrix s2 = add_param(x, y);
    std::puts("chain:"); Matrix s3 = add_chain(x, y);
}

go deeper

for a junior

Remember that returning a plain local name is cheapest, and that return a += b; copies even though it looks shorter.

for a middle

Explain why parameters are excluded from NRVO, how implicit move rescues return a;, and why an lvalue-reference expression gets neither.

for a senior

Spot hidden copies from ternaries, const locals and compound-assignment returns in review, and pick the operator+ shape that suits how callers pass operands.

for a principal

Set a team convention for value-returning operators and factories, backed by the -Wpessimizing-move and -Wredundant-move warnings in CI.

## The NRVO rule, read literally The copy-elision clause allows omitting the copy or move into the result object only when the `return` operand is **the name of a non-volatile object with automatic storage duration, other than a function parameter or a `catch` variable**. Every word excludes something real: - *the name*: `return a += b;`, `return std::move(r);` and `return c ? x : y;` are expressions, not names; - *automatic storage*: statics, globals and members of `*this` do not qualify; - *not a parameter*: the caller constructs by-value parameters, so they already have their own storage. ## Three `operator+` shapes The example defines three versions and logs each copy and move of a 512x512 `Matrix`: | Shape | NRVO | Implicit move | Clang output | |---|---|---|---| | `Matrix r = a; r += b; return r;` (both arguments `const Matrix&`) | yes | not needed | copy | | `Matrix operator+(Matrix a, const Matrix& b) { a += b; return a; }` | no, `a` is a parameter | yes | copy, move | | `Matrix operator+(Matrix a, const Matrix& b) { return a += b; }` | no, not a name | no, `Matrix&` is an lvalue | copy, copy | The first copy in every row is the unavoidable one: the sum needs its own storage. The parameter form is the textbook choice when callers often pass temporaries, because `x + y + z` then moves the intermediate result into the parameter instead of copying it. The third form looks shortest and is the slowest. ## Other ways NRVO is lost - **Two different locals returned on different paths.** In `Report a, b; if (c) return a; return b;` both objects are alive at once, so they cannot both live in the result object. Clang constructs both and moves the chosen one. - **A conditional expression.** `return c ? a : b;` with two lvalues yields an lvalue, so it copies. Rewrite it as an `if` with two `return` statements to get moves. - **A member, a global or a static.** These are not automatic objects, so they are copied unless you write `std::move` deliberately. - **A `const` local.** NRVO still works, but if it fails the implicit move binds `const Report&&` to the copy constructor, so the fallback is a copy. ## Implicit move: the safety net 1. **C++11**: a returned name of a local or by-value parameter is first treated as an rvalue, so a move constructor is preferred over a copy. 2. **C++20**: the rule was widened. A returned local can be moved into a *different* return type's constructor that takes an rvalue reference, for example a `Derived` local into `Base(Base&&)`, and parameters can be moved by `throw`. Clang 21 applied that widening in `-std=c++17` and earlier modes too in a test with a `Derived` local. 3. **C++23**: a move-eligible name in a `return` is now an **xvalue** outright. Code that relied on it being an lvalue changes: `int& g(int&& x) { return x; }` became ill-formed, and `std::string&& pass(std::string&& s) { return s; }` now compiles. The fallback therefore covers parameters and multiple named returns, but never expressions such as `a += b`, a member access such as `rep.rows`, or a dereference such as `*ptr`; those stay lvalues and are copied unless the code moves them explicitly. ## Checking a function in practice Constructor logging, as in the example, is the quickest way to see which rule fired, but production types rarely log. Two other techniques work on real code: - Delete the copy constructor in a test build (`Matrix(const Matrix&) = delete;`). Every return that needed a copy now fails to compile, with the line number. - Read the warnings: `-Wpessimizing-move` and `-Wredundant-move` point at `std::move` on returns; there is no warning for `return a += b;`, so that one has to be caught by the deleted-copy trick or a profiler. ## Writing `operator+` well - Take the left operand by value, modify it with `+=`, and `return a;` as its own statement. - Or take both by `const&`, build a local, and return the local by name. - Never `return a += b;` and never `return std::move(r);` for a local.

  • How do you return one of two locals chosen at run time without copying?
    Use two `return` statements, `if (c) return a; return b;`, not `return c ? a : b;`. The conditional expression is an lvalue and copies; each plain name is move-eligible, so the chosen local is moved. If you need NRVO rather than a move, restructure so a single local is returned on every path.
  • Why can a by-value parameter not be the result object, when a local can?
    The caller constructs a by-value parameter before the call, in storage the calling convention chooses, while the result object is a separate location the caller also provides. They exist at the same time, so they cannot be merged. A local is created inside the function, so the compiler can choose to place it in the result object's storage.

  • NRVO also applies when a function returns its by-value parameter.
  • return a += b; moves because a is a local parameter.
  • return c ? a : b; moves whichever local the condition selects.
  • If NRVO fails, a returned local is always copied.
  • Implicit move on return was introduced in C++20.

Assumes C++23 implicit-move rules: C++11 introduced implicit move on return, C++20 widened it to converting returns, and C++23 made move-eligible names xvalues; Clang 21 also applies the C++20 widening in older modes.