Copy Elision In C++

Copy elision is defined as an optimisation technique that is used to avoid the unnecessary copying of objects. Generally, all the compilers use the technique of copy elision. The optimisation technique is not available to a temporary object that is bound to a reference.

It is also known as copy omission.

Let us understand the need for copy elision with the help of an example.

Example

#include <iostream>
using namespace std;
class A
{
public:	
	A(const char* str = "\0") //default constructor
	{
		cout << " Default Constructor called" << endl;
	}	
	
	A(const A &a) //copy constructor
	{
		cout << "Copy constructor called" << endl;
	}
};

int main()
{
	A a1 = "copy me"; // Create object of class A
	return 0;
}

Output

Output

Default Constructor called

Observations

The program outputs the Default constructor . It happened because when we created object a1 one argument constructor is converted to copy me to a temp object and that temp object is copied to object a1.

This is how the statement -

A a1 = "copy me"

Is converted to

A a1("copy me")

How to avoid unnecessary overheads?

This problem of overhead is avoided by many compilers.

The modern compilers break down the statement of copy initialisation

A a1 = "copy me"

The statement of direct initialisation.

A a1("copy me")

which in turn calls the copy constructor.

Input Required

This code uses input(). Please provide values below: