0
考虑下面的例子:拷贝构造函数和运算符重载:C++
#include <iostream>
using namespace std;
class Test{
public:
int a;
Test(int a=0):a(a){ cout << "Ctor " << a << endl;}
Test(const Test& A):a(A.a){ cout << "Cpy Ctor " << a << endl;}
Test operator+ (Test A){
Test temp;
temp.a=this->a + A.a;
return temp;
}
};
int main()
{
Test b(10);
Test a = b ;
cout << a.a << endl;
return 0;
}
输出为:
$ ./Test
Ctor 10
Cpy Ctor 10
10
它调用拷贝构造函数。现在,假设如果我们修改代码:
int main()
{
Test b(10);
Test a = b + Test(5);
cout << a.a << endl;
return 0;
}
输出变为:
$ ./Test
Ctor 10
Ctor 5
Ctor 0
15
表达Test a = b + Test(5);
不会调用拷贝构造函数。我认为b+ Test(5)
应该用于实例化类型的新对象a
,所以这应该调用复制构造函数。有人可以解释输出吗?
由于
这可能在...之前得到了回答...请参阅“copy elision”http://en.wikipedia.org/wiki/Copy_elision,即允许编译器优化副本。 – ronag
请注意,在'operator +'中,你不需要'temp'。你可以直接使用'A'。 – juanchopanza
[什么是复制elision和返回值优化?](http://stackoverflow.com/questions/12953127/what-are-copy-elision-and-return-value-optimization) –