what is copy elision in C++? copy elision is a compiler optimization technique to avoid UN-necessary copying of an c++ object. According to wikipedia https://en.wikipedia.org/wiki/Copy_elision “The standard also describes a few situations where copying can be eliminated even if this would alter the program’s behavior, the most common being the return value optimization.”

Let us See below example:

#include<iostream>
using namespace std;

class C {
public:
	C() {cout << "Constructor called.\n";}
	C(const C&) { cout << "A copy was made.\n"; }
};

C f() {
	return C();
}

int main() {
	cout << "Hello World!\n";
	C obj = f();
	return 0;
}

When we compile and run the above program on most of the platform like window and Linux it will give output.

Hello World!
Constructor called.

we can prevent copy elision in c++ during compilation time using switch  -fno-elide-constructors.   Let us try to compile above program as g++ -fno-elide-constructors and run ,The output will be

Hello World!
Constructor called.
A copy was made.
A copy was made.
  •  cout << “Hello World!\n”  outputs Hello World!
  • C obj = f(); This instruction calls function f(), function f() is returning an object by value.  To return an object it will create an temporary object class C. To create an object of class C, it will calls its constructor and so is the output “Constructor called”.
  • When an object is returned from a function by value, copy constructor is getting called and so is the output “A copy was made”
  • Also we know the fact that copy constructor is used to create an object from existing object ( already created ). As f() will return an object and returned object is going to create new object c.

In this way from the above observation we can say that copy elision is an optimization technique done by the compiler to generate optimized code for faster execution of program.



Related Contents to follow