cpp core · medium

RVO & Copy Elision

Return-value optimization builds the result directly in the caller's slot, eliminating the copy/move; std::move on a return can disable NRVO.

🔑 Key line

RVO/copy elision constructs the returned object in the caller's storage - no copy/move (mandatory for prvalues since C++17). Don't std::move a return value.

The code

struct Widget { /* expensive to copy */
};
Widget make() {
Widget w; // a local
return w; // NRVO candidate
}
Widget obj = make(); // copy elision: obj built in place
// pitfall:
return std::move(w); // pessimization - can disable NRVO

What this lesson walks through

  1. 01Returning a big object by value
  2. 02Naive: build a local in make()
  3. 03...then move it out (+1)
  4. 04RVO: build directly in obj
  5. 05Mandatory for prvalues (C++17)
  6. 06NRVO for named locals
  7. 07Pitfall: don't std::move the return

make() returns a Widget by value, and main stores it in obj. Naively that sounds like: build a Widget, then copy it into obj. Does it really copy?

See it animated — step by step, at your own pace

Unlock the full interactive walkthrough of RVO & Copy Elision and 100+ animated C++ interview lessons.

← Previous
Move Semantics: Copy vs Move
Next →
noexcept Moves & Vector Growth