Copy elision, including Return Value Optimization (RVO), is a compiler optimization technique that eliminates unnecessary copies of objects. However, the degree to which copy elision is applied can vary depending on the compiler and the optimization settings used.
In C++17 and later, certain forms of copy elision are guaranteed by the language standard. Specifically, the standard requires that copy elision is performed in the following cases:
In these cases, the compiler must perform copy elision, and the copy or move constructors are not called.
Here's an example where copy elision is guaranteed:
MyClass createObject() {
// Guaranteed copy elision
return MyClass{};
}
int main() {
// No copy or move constructor called
MyClass obj = createObject();
}
However, in other cases, copy elision is still optional and depends on the compiler and optimization settings. For example:
MyClass createObject(bool flag) {
MyClass obj1, obj2;
// Optional copy elision
return flag ? obj1 : obj2;
}
In this case, the compiler may or may not perform copy elision when returning obj1
or obj2
, depending on its optimization capabilities and the settings used.
It's important to note that even if copy elision is not performed, the compiler is still allowed to optimize out the copy or move operations if they have no observable side effects.
To ensure maximum performance, it's generally recommended to:
By relying on guaranteed copy elision and enabling compiler optimizations, you can write efficient code that minimizes unnecessary copies and moves.
Answers to questions are automatically generated and may not have been reviewed.
Learn how to control exactly how our objects get copied, and take advantage of copy elision and return value optimization (RVO)