Introduction
The term "copy elision" refers to an optimization approach for avoiding the redundant copying of objects. Copy elision is a method used by almost all compilers. A temporary object tied to a reference is not eligible for the optimization strategy.
Copy omission is another name for it.
Let us take a look at the below example.
#include <iostream>
using namespace std;
class className
{
public:
className(const char *str = "\0")
{
cout << " Default Constructor " << endl;
}
className(const className &a)
{
cout << "Copy constructor " << endl;
}
};
int main()
{
className objectName = "copy me";
return 0;
}
Output:
Default Constructor
Default Constructor is outputted by the program. This is because, when we create an object of the class className, one argument constructor is used to convert the string “copy me” into the temporary object, and furthermore, that temporary object is copied to the object objectName.
Also Read - C++ Interview Questions
How to reduce overhead
Modern compilers normally are optimised to reduce the overhead. They do so by breaking down the statement of copy initialization.
className objectName = "copy me"
is broken down to
className objectName("copy me")
If we still want the compiler to not elide the call to copy constructor [disable copy elision], we may build the program using the "-fno-elide-constructors" option in g++.
Try and compile by yourself with the help of online C++ Compiler for better understanding.
Also read - Decimal to Binary c++