Copy elision is a strategy employed to prevent redundant object duplication, serving as an optimization method. Typically, compilers universally adopt this approach. However, copy elision optimization is not applicable to temporary objects associated with a reference.
It is also known as copy omission.
Let's explore the necessity of copy elision through an illustrative 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
Default Constructor called
Observations
The software displays the Default constructor output. This occurred due to the conversion of the single-argument constructor into a temporary object when creating object a1, followed by copying this temporary object 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 issue of overhead is circumvented by numerous compilers.
Modern compilers dissect the copy initialization statement.
A a1 = "copy me"
The statement of direct initialisation.
A a1("copy me")
which in turn calls the copy constructor.