簡體   English   中英

模板類中的析構函數給出錯誤

[英]Destructor in template class gives an error

我有一個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;

我不確定如何正確編寫賦值運算符以避免此錯誤。

我該如何解決這個問題,我對如何處理這個問題一無所知

正如評論中已提到的那樣:您需要一份深層副本。

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))
{ };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM