Copy elision in C++

Hello Learners, today we are going to learn a very interesting topic that is copy elision in C++. Copy elision is also known as return value optimization, almost all the compilers use this technique to eliminate the unnecessary copying of objects.

C++: Program for Copy elision

Now let’s understand the copy elision concept with the help of an example and code,

Code:

#include<iostream>
using namespace std;
class d
{
private:
int a,b,sum;
public:
d()
{
cout<<"enter the values of a and b:";
cin>>a>>b;
}
d(const d&)
{
sum=a+b;
cout<<"sum="<<sum<<endl;
}
};
d f()
{
return d();
}
int main()
{
int sum;
cout<<"hello! this is an copy elision program:\n";
d obj=f();
}

Output:

hello! this is an copy elision program:
enter the values of a and b: 23

In the above code, everyone will be thinking, the output will the sum of the two numbers also it’s wrong. If you carefully observe the code,  copy constructor will not be called so the addition of the two numbers will not occur. Because it is returning the “d()”, and this method is known as return value optimization (or) copy elision.

The main purpose of using copy elision( copy omission) is that, it is used to reduce the avoid unnecessary copying.

Also read: How to prevent object copy in C++

Leave a Reply