用于合并数组的重载运算符+失败

时间:2014-03-21 19:30:35

标签: c++ c++11

我试图理解复制和交换习惯用法,但当我使用operator+Dumb_array c(a+b) a = a + b时,我的程序会崩溃。< / p>

#include "stdafx.h"
#include <iostream>

using std::cout; using std::endl;

class Dumb_array {
    int* _array;
    int _size;
public:
    Dumb_array(size_t s)
        : _size(s), _array(_size ? new int[s]() : nullptr) {
        cout << "default constructor" << endl;
    }
    Dumb_array(const Dumb_array & other)
        : _size(other._size), _array(_size ? new int[other._size]() : nullptr) {
        cout << "copy constructor" << endl;
        std::copy(other._array, other._array + sizeof(int) * _size, _array);
    }

    ~Dumb_array() {
        cout << "destructor" << endl;
        delete[] _array;
    }
    Dumb_array& operator=(Dumb_array a) {
        cout << "assigment" << endl;
        swap(*this, a);
        return *this;
    }
    Dumb_array operator+(Dumb_array& const other) const {
        cout << "+" << endl;
        int new_size = _size + other._size;
        Dumb_array sum(new_size);
        int i;
        for (i = 0; i < _size; i++)
            sum._array[i] = _array[i];
        for (int j = 0; j < other._size; j++, i++)
            sum._array[i] = other._array[j];
        return sum;
    }
    friend void swap(Dumb_array& one, Dumb_array& another);
};
void swap(Dumb_array& one, Dumb_array& another) {
    std::swap(one._size, another._size);
    std::swap(one._array, another._array);
}

int _tmain(int argc, _TCHAR* argv[]) {
    Dumb_array a(2);
    Dumb_array b(a);
    // Dumb_array c(a+b);
    a = a + b;
    std::system("pause");
    return 0;
}

1 个答案:

答案 0 :(得分:1)

std::copy(other._array, other._array + sizeof(int)*_size, _array);

那个sizeof(int)是不必要的。您指向了other._array末尾之外的内存位置。正确的行是......

std::copy(other._array, other._array + _size, _array)

我希望能解决您的问题。你应该弄清楚如何使用调试器,它对这些问题有很大的帮助。

相关问题