skip to content

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.