以前写拷贝构造函数的时候,觉得参数为引用,不为值传递,仅仅是为了减小一次内存拷贝。然而今天看到一篇文章发现本身对拷贝构造的参数理解有误。 参数为引用,不为值传递是为了防止拷贝构造函数的无限递归,最终致使栈溢出。函数
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 _tmain(int argc, _TCHAR* argv[])
{
test ort;
test a(ort);
test b = ort ;
a = b;
return 0;
}
test(test t);
test ort;
test a(ort); --> test.a(test t=ort)==test.a(test t(ort))
-->test.a(test t(test t = ort))
==test.a(test t(test t(ort)))
-->test.a(test t(test t(test t=ort)))
就这样会一直无限递归下去。
class test
{
public:
test()
{
cout << "constructor with argument\n";
}
~test()
{
}
test(test& t)
{
cout << "copy constructor\n";
}
test&operator=(test e)
{
cout << "assignment operator\n";
return *this;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
test ort;
test a(ort);
test b = ort ;
a = b;
return 0;
}