看到这个题目,第一反应原因是,为了减少一次内存拷贝。
但是我看了别人的博客才知道,这样做为了防止拷贝构造函数的防止无限递归,导致栈溢出。
1.构造函数
#include <iostream>
using namespace std;
class test
{
public:
test()
{
cout << "constructor with argument\n";
}
~test()
{
}
test(test& t)
{
cout << "copy constructor\n";
}
test&operator=(const test&e)
{
cout << "assignment operator\n";
return *this;
}
};
int main()
{
test ort;
test a(ort);
test b = ort;
a = b;
system("pause");
return 0;
}
结果:
constructor with argument
copy constructor
copy constructor
assignment operator
解释:
test ort ,ort调用无参构造函数;
test a(ort),a调用拷贝构造函数;
test b = ort,b调用拷贝构造函数
a = b,a调用赋值函数
这里拷贝构造函数和赋值函数的区别就是:
当b没有初始化的时候,调用拷贝构造函数
当a已经初始化的时候,调用赋值函数。
2.为什么值传递会无限递归?
如果用值传递,构造函数如下:
test(test t)
因为无法通过编译,所以没有代码。
那么理论上:
test ort;
test a(ort) --->先调用拷贝构造函数变成
test a(t=ort)--->调用赋值函数===这里赋值又调用拷贝构造函数
test a( test t(ort))--->括号里面调用拷贝构造函数
。。。这里就无限递归
3.那把赋值构造函数的参数传入方式变成值传递呢?
#include <iostream>
using namespace std;
class test
{
public:
test()
{
cout << "constructor with argument\n";
}
~test()
{
}
test(test &t)
{
cout << "copy constructor\n";
}
test&operator=(const test e)
{
cout << "assignment operator\n";
return *this;
}
};
int main()
{
test ort;
test a(ort);
test b = ort;
a = b;
system("pause");
return 0;
}
结果:
constructor with argument
copy constructor
copy constructor
copy constructor
assignment operator
这里多了一个拷贝构造函数,为什么呢?
解释:
因为在我们把a = b,a调用赋值函数函数test&operator=(const test e)的时候
b到e传递过程,会调用一次拷贝构造函数;
但是当e是引用的时候,就不会调用构造函数。