重载+号运算符代码中是返回的一个临时对象,按理说会调用一次拷贝,为什么没调用?
代码如下:
#include <iostream>
using namespace std;
class test
{
friend test operator+(test& a);
public:
//拷贝构造函数
test(const test& t){
cout<<"拷贝构造函数执行"<<endl;
this->value=t.value;
}
//移动拷贝构造函数
test(const test&& t){
cout<<"移动拷贝构造函数执行"<<endl;
this->value=t.value;
}
explicit test(int v){
cout<<"构造函数执行"<<v<<endl;
this->value=v;
}
~test(){
cout<<"析构函数执行"<<this->value<<endl;
}
test operator+(test& a){
int tmp = a.value + this->value;
test t(tmp);
return t;
}
int getValue(){
return this->value;
}
private:
int value;
};
int main()
{
test t1(4);
test t2(5);
test t3 = t1+t2;
cout<<t3.getValue()<<endl;
return 0;
}
程序输出:
构造函数执行4
构造函数执行5
构造函数执行9
9
析构函数执行9
析构函数执行5
析构函数执行4
输出是
constructor4
constructor5
copy constructor5
copy constructor4
constructor9
tmp constructed!
0x28ff08
~test()4
~test()5
0x28ff08
9
copy constructor4
copy constructor4
~test()4
~test()4
~test()9
~test()5
~test()4
编译器进行了优化
可以看出t的地址和t3的地址是相同的,也就是说没有进行拷贝构造
我加了一个f(),其中参数x是拷贝构造过来的,编译器不会将这个参数直接放到t4的地址上,因此此处调用了拷贝构造函数。
而在operator+()中,编译时是可以发现t构造出了之后直接赋给t3,因此进行了优化。