Developer knowledge network · moderated exchange

Супольнасць UnreliableCode

Супольнасць распрацоўшчыкаў даследаванняў, зваротнага праектавання і кадавання

Knowledge indexжыць
4Categories
919Threads
2.8KПаведамленні
Discussion

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

modern_cpp_artisan
C++ Template Wizard
MEMBER
прадстаўнік: 124
Дата далучэння: Jun 2019
Паведамленні: 29
Дзякуй: 72
1 месяцаў таму · 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
прадстаўнік: 190
Дата далучэння: Aug 2020
Паведамленні: 20
Дзякуй: 22
1 месяцаў таму · 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
прадстаўнік: 146
Дата далучэння: Aug 2019
Паведамленні: 33
Дзякуй: 31
1 месяцаў таму · Jul 14, 2026 11:54 PM
#3

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