C++ 库研究笔记——拷贝构造函数的一个错误范例

之前记录的有:

 

C++库研究笔记——赋值操作符operator=的正确重载方式(三个准则)

我原来的拷贝构造函数是这样写的:

    explicit array1d(Index size=0,T val=T())
        :size_(size),data_(0)
    {
        log_info("construct 1");
        if(size==0)
            return;

        allocate(); // allocate memory

        for(int i=0; i<size_; i++){
            data_[i]=val;
        }
    }

// 这样写的本意是:为了能够使用 std::vector<T> v_other; array1d<T> v(v_other);
    template<class ArrayType>
    array1d(const ArrayType& other)
    {
        log_info("arrayType");
        size_= other.size();
        allocate();
        // copy value
        for(int i=0; i<size_; i++){
            data_[i]=other[i];
        }
    }


经过测试:

    std::vector<real> v(3,9.0);
    array1d<real> b(v);
    b.print();

确实没有问题


但是:

    array1d<float, long> dl(9l);
    dl[3]=4;
    dl.print("dl");

    // 
    array1d<float, long> dl2(dl);
    dl2.print("dl2");

编译没有问题,运行时会出现,double free memory

*** glibc detected *** ./main: double free or corruption (fasttop): 0x0000000001b85010 ***

通过追踪发现:

上面的代码根本没有调用

    template<class ArrayType>
    array1d(const ArrayType& other)
    {
        log_info("arrayType");
        size_= other.size();
        allocate();
        // copy value
        for(int i=0; i<size_; i++){
            data_[i]=other[i];
        }
    }
而是, 直接原始的拷贝,这样就会拷贝一个相同的数据指针位置,然后在相同的位置释放两次内存

解决办法:(追加如下代码)

    array1d(const array1d & other)
    {
        log_info("array1d&");
        size_= other.size();
        allocate();
        // copy value
        for(int i=0; i<size_; i++){
            data_[i]=other[i];
        }
    }





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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值