What are copy elision and return value optimization?

C++Server Side ProgrammingProgramming

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.

raja
Published on 28-Feb-2018 06:50:14
Advertisements