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

SAS*_*ROG 3 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;
    }
Run Code Online (Sandbox Code Playgroud)

直到我尝试完成作业为止

Array<int> g;
Array<int> i(3);
i[1] = 99;
g = i;
Run Code Online (Sandbox Code Playgroud)

然后我得到一个错误

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
Run Code Online (Sandbox Code Playgroud)

显然来自这里的析构函数

delete[] this->_array;
Run Code Online (Sandbox Code Playgroud)

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

Aco*_*gua 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
};
Run Code Online (Sandbox Code Playgroud)

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

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;
};
Run Code Online (Sandbox Code Playgroud)

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

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

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

Array(Array&& other)
    : _array(std::exchange(other._array, nullptr)),
      _arrSize(std::exchange(other._arrSize, 0))
{ };
Run Code Online (Sandbox Code Playgroud)