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 |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |