I was studying how a function returns an object by means of return-by-value. So, to test the theory, I ran a simple program that had a function returning an instance of myclass – a custom-made class.
#include <iostream>
#include <cstdio>
using namespace std;
class myclass {
int i;
public:
void set_i(int n) { i=n; }
~myclass();
};
myclass f(int k); // return object of type myclass
int main()
{
f(20);
return 0;
}
myclass f(int k)
{
myclass x;
x.set_i(k);
return x;
}
myclass::~myclass() {
cout << "hello\n";
}
I overloaded the destructor by placing a cout “hello” statement in it so that I would be able to track when the object’s local copy within the function as well as the temporary object created during execution of the return statement were destroyed.
So, I was expected 2 calls to the destructor; one for the function’s local copy of the object and one for the temporary object. But instead, I received only one!
Please share why my program did not output “hello” twice.
Thanks.
That is an effect of return value optimization which eliminates the temporary object created to hold a function’s return value. This optimizes out the redundant copy constructor and destructor calls.