Developer knowledge network · moderated exchange

Społeczność UnreliableCode

Badania programistów, inżynieria wsteczna i społeczność programistów

Knowledge indexNa żywo
4Categories
919Threads
2.8KPosty
Discussion

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

modern_cpp_artisan
C++ Template Wizard
MEMBER
Rozpustnik: 124
Data dołączenia: Jun 2019
Posty: 29
Dzięki: 72
1 miesięcy temu · 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
Rozpustnik: 190
Data dołączenia: Aug 2020
Posty: 20
Dzięki: 22
1 miesięcy temu · 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
Rozpustnik: 146
Data dołączenia: Aug 2019
Posty: 33
Dzięki: 31
1 miesięcy temu · Jul 14, 2026 11:54 PM
#3

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