复制构造函数和运算符重载:C++

Copy Constructor and Operator Overloading : C++

本文关键字:C++ 重载 运算符 构造函数 复制      更新时间:2023-10-16

考虑以下示例:

#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

它调用Copy构造函数。现在,假设我们将代码修改为:

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)应该用于实例化Test类型的新对象a,所以这应该调用复制构造函数。有人能解释一下输出吗?

感谢

请参阅副本省略:http://en.wikipedia.org/wiki/Copy_elision

基本上,并没有构造任何temp,而是将结果直接放入测试对象中。