What are copy elision and return value optimization?


Copy elision is an optimization implemented by most compilers to prevent extra (potentially expensive) copies in certain situations. So if you have some code that is creating objects not being used or don't have side effects, 

example

struct MyStruct {
   MyStruct() {}
   MyStruct(const MyStruct&) {
      std::cout << "Copied.\n";
   }
};
MyStruct f() {
    return MyStruct();
}
int main() {
   std::cout << "Main\n";
   MyStruct obj = f();
}

Output

You could get any of following outputs based on compiler and settings −

Main

Main
Copied
Copied

Main
Copied

This means fewer objects than you expect can be created, so you also can't rely on a specific number of constructors and destructors being called. You shouldn't have critical logic inside copy/move-constructors or destructors, as you can't rely on them being called.

Updated on: 11-Feb-2020

282 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements