What is copy elision and RVO in C++?

When a function returns an object, the compiler can build it directly in the place of the caller, with no copy and no move. This is copy elision. Since C++17 it is guaranteed when you return a temporary (a prvalue). With a named local variable (NRVO) it is allowed, and most compilers do it.

#include <iostream>

struct Noisy {
    Noisy() { std::cout << "construct\n"; }
    Noisy(const Noisy&) { std::cout << "copy\n"; }
    Noisy(Noisy&&) noexcept { std::cout << "move\n"; }
};

Noisy make() { return Noisy(); }                 // guaranteed: no copy, no move

int main() {
    Noisy n = make();
}
Output

construct

So return std::move(local); is a mistake: it can stop the elision. Just write return local;. See Move Semantics.


Learn more about the similar topics:
Tutorials
C++ Lambda Expressions
C++ Move Semantics and the Rule of Five
Modern C++ Features: ranges, optional, variant and format
C++ Multithreading: thread, mutex and async
Exercises & Assignments
Filter and sum numbers with algorithms and ranges
Interview Questions & Answers
What is the Rule of Three, Five and Zero in C++?
What does std::move do in C++?
What are concepts in C++20?
What is perfect forwarding in C++ (std::forward)?
How do lambda captures work in C++?
What is new in C++20?
What is new in C++23?