wiki:cpp-copy-elision
Table of Contents
C++ Copy elision
Copy elision is a compiler optimization that eliminates unnecessary copy or move operations when a temporary object is constructed directly into its destination. In C++17 and later, copy elision is guaranteed in certain contexts (like returning a temporary from a function), making it semantically part of the language, not just an optimization.
Copy elision improves performance automatically; rely on it but don't make code depend on side effects of copy constructors running or not running.
Example
This example shows how the compiler elides copies when returning temporaries.
// compile: g++ -std=c++17 -o elision elision.cpp // run: ./elision // description: copy elision eliminates unnecessary copies of temporaries #include <iostream> #include <string> class Widget { public: Widget() { std::cout << "Default constructor\n"; } Widget(const Widget&) { std::cout << "Copy constructor\n"; } Widget(Widget&&) { std::cout << "Move constructor\n"; } }; Widget makeWidget() { Widget w; return w; // copy elision: w constructed directly in return value } int main() { Widget w = makeWidget(); // copy elision: temporary constructed directly into w return 0; }
wiki/cpp-copy-elision.md · Last modified: (external edit)
