标签:[] com lang with border 偏差 溢出 复制 code
之前写拷贝构造函数的时候,以为参数为引用,不为值传递,仅仅是为了减少一次内存拷贝。然而今天看到一篇文章发现自己对拷贝构造的参数理解有误。 参数为引用,不为值传递是为了防止拷贝构造函数的无限递归,最终导致栈溢出。
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;}
C++ 为什么拷贝构造函数参数必须为引用?赋值构造函数参数也必须为引用吗?
标签:[] com lang with border 偏差 溢出 复制 code
原文地址:http://www.cnblogs.com/zsq1993/p/6110773.html