I compile the c++ code using the follow command to disable return value.
g++ -fno-elide-constructors rvoptimazation.cpp -o test
But the output of ./test is
10
10
10
13
0xbfdf0020
13
I am confused by the last call of the constructor. Can anyone explain which line of the code will call the constructor after return in operator*? Thanks in advance.
#include<iostream>
using namespace std;
class Rational{
public:
Rational(int x ,int y){
_a = x;
_b = y;
cout << __LINE__ << endl;
}
Rational(Rational const &t){
cout << __LINE__ << endl;
}
Rational operator*(Rational const &t){
Rational re = Rational(_a * t._a ,_b * t._b);
cout << &re << endl;
return re;
//return *this;
}
Rational get()
{
return *this;
}
public:
int _a ,_b;
};
int main()
{
Rational r1(1 ,2);
Rational r2(2 ,3);
r1 * r2;
// cout << &r3 << endl;
}
operator*returns by value, so the returned object must be constructed. The statementreturn recalls the copy constructor to do that.I think the explanation at Return value optimization is quite clear.