Developer knowledge network · moderated exchange

UnreliableCode-Community

Community für Entwicklerforschung, Reverse Engineering und Codierung

Knowledge indexLive
4Categories
919Threads
2.8KBeiträge
Discussion

How Copy Elision and Guaranteed Return Value Optimization (RVO) work in C++17 [StackOverflow Architecture Guide]

modern_cpp_artisan
C++ Template Wizard
MEMBER
Vertreter: 124
Beitrittsdatum: Jun 2019
Beiträge: 29
Danke: 72
Vor 1 Monaten · Jul 14, 2026 3:37 AM
#1

In C++17, Return Value Optimization (RVO) became a language guarantee rather than an optional compiler optimization:

CPP
std::vector<int> MakeVector() {
    return std::vector<int>(1000000, 42); // Guaranteed RVO (No copy, no move!)
}

std::vector<int> v = MakeVector();

The compiler constructs the vector directly inside the storage location allocated for v on the caller's stack frame. Neither the copy constructor nor the move constructor is ever invoked!

raii_clean_coder
Modern C++ Advocate
MEMBER
Vertreter: 190
Beitrittsdatum: Aug 2020
Beiträge: 20
Danke: 22
Vor 1 Monaten · Jul 14, 2026 5:49 AM
#2

Crucial tip: Never write return std::move(v); on a local variable being returned by value! Doing so actually inhibits NRVO (Named RVO) and forces a move instead of zero-cost in-place construction.

profiler_pat
Performance Hunter
MEMBER
Vertreter: 146
Beitrittsdatum: Aug 2019
Beiträge: 33
Danke: 31
Vor 1 Monaten · Jul 14, 2026 11:54 PM
#3

Returning std::move(local) is one of the most common anti-patterns in junior C++ code.