cpp17 · advanced
C++17: Guaranteed Copy Elision
C++17 reframes prvalues and makes their copy elision mandatory rather than a permitted optimization: a prvalue is now a 'recipe' that materializes into an object only where one is needed, so return T(); and T x = make(); construct the object directly in the destination with no copy or move — even conceptually. Because no copy or move is required, a type may have both its copy and move constructors deleted and still be returned by value from a factory, which enables zero-overhead factories for immovable types (scope guards, mutex-like wrappers, types holding references). The crucial distinction for interviews: this guarantee applies only to prvalues. Named Return Value Optimization — returning a named local with return obj; — remains an optional optimization that still requires an accessible move or copy constructor as a fallback, so it is wrong to claim every return is guaranteed to elide.
C++17 guaranteed copy elision: prvalue elision is mandatory (return T(); builds directly in the target, even with copy+move deleted) so factories can return immovable types by value — but NRVO on a named local stays optional.
The code
struct Big { Big(); Big(const Big&) = delete; Big(Big&&) = delete;};
Big make() { return Big();} // OK in C++17! no copy/move neededBig b = make(); // OK: constructed directly into b
// A prvalue is now 'a recipe to construct', materialized only when needed// Pre-C++17 this required an accessible copy/move ctor (even if elided).What this lesson walks through
- 01Prvalues no longer copy
- 02What it enables
- 03Gotcha — only prvalues are guaranteed
- 04Elision vs NRVO — know the line
In C++17, copy elision for prvalues is mandatory, not an optimization. Returning a temporary (return Big();) and initializing from one (Big b = make();) construct the object directly in the destination — no copy or move ever happens, even conceptually. This is the new prvalue model: a prvalue is a 'recipe' that materializes into an object only where one is needed.
See it animated — step by step, at your own pace
Unlock the full interactive walkthrough of C++17: Guaranteed Copy Elision and 100+ animated C++ interview lessons.