模板类中的析构函数给出错误

时间:2019-06-14 12:59:09

标签: c++ templates

我有一个Array模板类,看起来像这样

template <typename T>

class Array {
   private:
    T *_array;
    int _arrSize;

   public:
    Array<T>() : _arrSize(0) {
        T *a = new T[0];
        this->_array = a;
    };

    Array<T>(unsigned int n) : _arrSize(n) {
        T *a = new T[n];
        this->_array = a;
    };

    Array<T>(Array<T> const &copy) : _array(copy._array), _arrSize(copy._arrSize) {
        *this = copy;
        return;
    };

    template <typename G>
    Array<T> &operator=(Array<G> const &rhs) {
        if (&rhs != this) {
            Array<T> tmp(rhs);
            std::swap(*this, tmp);
        }
        return *this;
    };

    ~Array<T>() {
        delete[] this->_array;
        this->_array = NULL;
    };

    T &getArray() const {
        return this->_array;
    }

在我尝试完成作业之前,哪个方法都能正常工作

Array<int> g;
Array<int> i(3);
i[1] = 99;
g = i;

然后我得到一个错误

array(99457,0x10f5f25c0) malloc: *** error for object 0x7fc390c02aa0: pointer being freed was not allocated
array(99457,0x10f5f25c0) malloc: *** set a breakpoint in malloc_error_break to debug
zsh: abort      ./array

显然来自这里的析构函数

delete[] this->_array;

我不确定如何正确编写赋值运算符来避免此错误。

1 个答案:

答案 0 :(得分:8)

  

我该如何解决,如何处理仍是空白

正如评论中已经提到的:您需要一个深层副本。

Array(Array const& copy) : _array(new T[copy._arrSize]), _arrSize(copy._arrSize)
// create a NEW array here:           ^
{
    //now you need to copy the data:
    std::copy(copy._array, copy._array + _arrSize, _array);
    // or implement a loop, if you are not allowed to use std::copy
};

您可能还实现了移动语义:

Array(Array&& other)    : _array(other._array), _arrSize(other._arrSize)
// now this object 'steals' the data  ^
{
    // now this is the owner of the data – but you still need to make sure that
    // the data is not owned TWICE, so:
    other._array = nullptr; // I'd prefer this over an empty array – but you should
                            // adjust the other constructor then as well
                            // side note: you CAN safely delete a nullptr, so no
                            // special handling in destructor necessary
    other.arrSize = 0;
};

实际上,您可以使其更简单:

Array(Array&& other)    : Array()
// constructor delegation  ^
// (creates an EMPTY Array)
{
    // and now you can just:
    std::swap(*this, other)
};

另一个变体(感谢JeJo,提示):

Array(Array&& other)
    : _array(std::exchange(other._array, nullptr)),
      _arrSize(std::exchange(other._arrSize, 0))
{ };