Developer knowledge network · moderated exchange

مجتمع الكود غير الموثوق به

أبحاث المطورين، مجتمع الهندسة العكسية والترميز

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 months ago · 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 months ago · 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 months ago · Jul 14, 2026 11:54 PM
#3

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