Cpp / 拷贝构造函数的参数为什么必须使用引用类型

表面原因:编译器无法通过,会报如下错误:

error: invalid constructor; you probably meant ‘CExample (const CExample&)’
     CExample(CExample ex) //拷贝构造函数

深层次原因是避免拷贝构造函数无限制的递归下去。 

栗子:

#include <iostream>

class CExample
{
    int m_nTest;

public:
    CExample(int x) : m_nTest(x)
    {
        std::cout << "constructor with argument\n";
    }

    CExample(const CExample &ex)
    {
        m_nTest = ex.m_nTest;
        std::cout << "copy constructor\n";
    }

    CExample &operator=(const CExample &ex)
    {
        std::cout << "assignment operator\n";
        m_nTest = ex.m_nTest;
        return *this;
    }

    void myTestFunc(CExample ex)
    {
    }
};

int main()
{
    CExample aaa(2);   // 输出:constructor with argument
    CExample bbb(3);   // 输出:constructor with argument
    bbb = aaa;      // 输出:assignment operator
    CExample ccc = aaa; // 输出:copy constructor
    bbb.myTestFunc(aaa);  // 输出:copy constructor

    return 0;
}

假设拷贝构造函数是传值的,那么在执行如下代码:

CExample ccc = aaa;

会将 aaa 传值到形参,此时构造形参实例时会调用拷贝构造函数,这就造成了无限地构造下去,直至堆栈耗尽,所以为了避免这个问题的发生,直接从编译器的角度禁用了该问题。

 

参考:拷贝构造函数的参数为什么必须使用引用类型_『小猪呼噜噜』的专栏 -- I Write,therefore I am.-CSDN博客_拷贝构造函数的参数

(SAW:Game Over!) 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值