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 NRVOWhat this lesson walks through
- 01Returning a big object by value
- 02Naive: build a local in make()
- 03...then move it out (+1)
- 04RVO: build directly in obj
- 05Mandatory for prvalues (C++17)
- 06NRVO for named locals
- 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.