C++ 为什么拷贝构造函数参数必须为引用?赋值构造函数参数也必须为引用吗?

    之前写拷贝构造函数的时候,以为参数为引用,不为值传递,仅仅是为了减少一次内存拷贝。然而今天看到一篇文章发现自己对拷贝构造的参数理解有误。 参数为引用,不为值传递是为了防止拷贝构造函数的无限递归,最终导致栈溢出。

    下面来看一个例子:
  1. class test
  2. {
  3. public:
  4. test()
  5. {
  6. cout << "constructor with argumentn";
  7. }
  8. ~test()
  9. {
  10. }
  11. test(test& t)
  12. {
  13. cout << "copy constructorn";
  14. }
  15. test&operator=(const test&e)
  16. {
  17. cout << "assignment operatorn";
  18. return *this;
  19. }
  20. };
  21. int _tmain(int argc, _TCHAR* argv[])
  22. {
  23. test ort;
  24. test a(ort);
  25. test b = ort ;
  26. a = b;
  27. return 0;
  28. }
输出:C++ 为什么拷贝构造函数参数必须为引用?赋值构造函数参数也必须为引用吗?
如果这些知识你都能理解。下面就来解释一下为什么值传递会无限递归!
如果复制构造函数是这样的 : 
  1. test(test t);
我们调用
  1. test ort;
  2. test a(ort); --> test.a(test t=ort)==test.a(test t(ort))
  3. -->test.a(test t(test t = ort))
  4. ==test.a(test t(test t(ort)))
  5. -->test.a(test t(test t(test t=ort)))
  6. ...
  7.     就这样会一直无限递归下去。
到这里,我们也就明白了,为什么拷贝构造函数的参数一定要为引用,不能为值传递的原因了。
接下来,我们再测试一下赋值构造函数的参数,如果我们把它的参数也改为值传递,做一个测试。
  1. class test
  2. {
  3. public:
  4. test()
  5. {
  6. cout << "constructor with argumentn";
  7. }
  8. ~test()
  9. {
  10. }
  11. test(test& t)
  12. {
  13. cout << "copy constructorn";
  14. }
  15. test&operator=(test e)
  16. {
  17. cout << "assignment operatorn";
  18. return *this;
  19. }
  20. };
  21. int _tmain(int argc, _TCHAR* argv[])
  22. {
  23. test ort;
  24. test a(ort);
  25. test b = ort ;
  26. a = b;
  27. return 0;
  28. }
输出:C++ 为什么拷贝构造函数参数必须为引用?赋值构造函数参数也必须为引用吗?
赋值构造函数如果为值传递,仅仅是多了一次拷贝,并不会无限递归。
总结:拷贝构造函数的参数必须为引用。赋值构造函数参数既可以为引用,也可以为值传递,值传递会多一次拷贝。因此建议赋值构造函数建议也写为引用类型。(CKK看 刚才我的理解还是有偏差:左右值不是关键,减少拷贝次数提高赋值效率是重点)

原文链接: https://www.cnblogs.com/chengkeke/p/5417362.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    C++ 为什么拷贝构造函数参数必须为引用?赋值构造函数参数也必须为引用吗?

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/232259

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月13日 下午3:25
下一篇 2023年2月13日 下午3:25

相关推荐