1. 首先看下下面一个例子
<span style="font-size:14px;">#include <iostream>
using namespace std;
class Rational
{
friend const Rational operator+(const Rational& a, const Rational& b);
public:
Rational(int a = 0, int b = 1): m(a), n(b)
{
cout << "Rational::Rational(int, int)" << endl;
}
Rational(const Rational& r): m(r.m), n(r.n)
{
cout << "Rational::Rational(const Rational&)" << endl;
}
Rational& operator=(const Rational& r)
{
if (this == &r)
return *this;
m = r.m;
n = r.n;
cout << "Rational::operator=(const Rational&)" << endl;
return *this;
}
private:
int m;
int n;
};
const Rational operator+(const Rational& a, const Rational& b)
{
cout << "operator+() begin"<< endl;
Rational temp;
temp.m = a.m + b.m;
temp.n = a.n + b.n;
cout << "operator+() end"<< endl;
return temp;
}
int main(void)
{
Rational r, a(10, 10), b(5,8);
r = a + b;
return 0;
}
运行结果:
[root@f8s optmize]# g++ temp_object_return_value.cpp -o temp_object_return_value
[root@f8s optmize]# ./temp_object_return_value
Rational::Rational(int, int)
Rational::Rational(int, int)
Rational::Rational(int, int)
operator+() begin
Rational::Rational(int, int)
operator+() end
Rational::operator=(const Rational&) // 疑问,这里之前,应该调用拷贝构造函数,但是实际上没有调用
[root@f8s optmize]#</span>
2. 增加编译选项( -fno-elide-constructors),看看结果
<span style="font-size:18px;">[root@f8s optmize]# g++ temp_object_return_value.cpp -o temp_object_return_value -fno-elide-constructors
[root@f8s optmize]# ./temp_object_return_value
Rational::Rational(int, int)
Rational::Rational(int, int)
Rational::Rational(int, int)
operator+() begin
Rational::Rational(int, int)
operator+() end
Rational::Rational(const Rational&) // 看,这里调用到拷贝构造函数,怎么回事
Rational::operator=(const Rational&)
[root@f8s optmize]#</span>
3. 查看gcc的手册,有这样的解释
到这里,疑惑解决。-felide-constructors这是默认选项。当产生的代码所调用的函数按值返回一个对象时,如果能直接在返回的位置上产生对象,而不是复制构造函数中已构建的对象,这将使代码大大简化。 但如果构造函数具有副作用,这也会引发问题,可以利用 -fno-elide-constructors 关闭这一选项。