[英]Copy Constructor and Operator Overloading : C++
Consider Below example: 考虑以下示例:
#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;
}
The Output is: 输出是:
$ ./Test
Ctor 10
Cpy Ctor 10
10
It calls Copy constructor. 它调用Copy构造函数。 Now, suppose If we modify the code as:
现在,假设我们将代码修改为:
int main()
{
Test b(10);
Test a = b + Test(5);
cout << a.a << endl;
return 0;
}
The Output becomes: 输出变为:
$ ./Test
Ctor 10
Ctor 5
Ctor 0
15
The expression Test a = b + Test(5);
表达式
Test a = b + Test(5);
does not call copy constructor. 不会调用复制构造函数。 What I thought that that
b+ Test(5)
should be used to instantiate a new object a
of type Test
, so this should call copy constructor. 我以为那
b+ Test(5)
应使用实例化一个新的对象a
类型的Test
,所以这应该调用拷贝构造函数。 Can someone explain the output? 有人可以解释输出吗?
Thanks 谢谢
See copy elision: http://en.wikipedia.org/wiki/Copy_elision 请参阅copy elision: http : //en.wikipedia.org/wiki/Copy_elision
Basically, no temp is constructed and result is put directly into Test a object. 基本上,没有构造temp,结果直接放入Test对象中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.