从数组中删除单元格给我运行时错误

remove a cell from array give me run time error

本文关键字:运行时错误 单元格 删除 数组      更新时间:2023-10-16

我有一个包含保存数据的单元格的模板数组,在代码中描述:

template <class T>
class Array
{
private:
    //the array is consist cellss that holds the data
    template<class S>
    class Cell
    {
    public:
        //members:
        S* m_data;
        //methods:
        //C'tor:(inline)
        Cell(S* data=NULL): m_data(data){};
        //D'tor:(inline)
        ~Cell(){delete m_data;};
        //C.C'tor:(inlnie)
        Cell(const Cell<S>& cell):  m_data(cell.m_data){};
    };
private:
    //members of Array:
    Cell<T>* m_head,*m_last;
    unsigned int m_size;
public:
    /*******************C'tors and D'tors************************/
    //C'tor:(inline)
    Array():m_head(NULL),m_last(NULL), m_size(0){};
    //D'tor:
    ~Array(){delete[] m_head;};
    //C.C'tor:
    Array(const Array& array): m_head(array.m_head),m_last(array.m_last),m_size(array.m_size){};
    /****************Adding********************/
    //add an element to the end of the Array:
    void add(const T added);
    /*******************Returning and deleting***********************/
    T& operator[](const unsigned int index)const {return *(m_head[index].m_data);};
    //delete the last element:
    void remove();
    /*********************Size*****************************/
    //returning the number of elements:(inline)
    const unsigned int size()const{return m_size;};
    //check if the Array is empty:
    bool isEmpty()const {return (m_size==0);};

};

现在这是add的实现:(经过测试看起来很好,但只是为了以防万一,我也写在这里)

template <class T>void Array<T>::add(const T added)
{
    //allocating memory for the new array:
    Cell<T>* newarray=new Cell<T>[m_size+1];
    //copy all the elements from the old array:
    unsigned int i;
    for (i=0; i<m_size;i++)
        newarray[i].m_data=m_head[i].m_data;
    //put the added in the last index:
    T* newelement= new T(added);
    newarray[i].m_data=newelement;
    //change the ptrs:
    m_head=newarray;
    m_last=&newarray[m_size];
    //increase the counter:
    m_size++;
}

,这是remove:

的实现
template <class T>void Array<T>::remove()
{
    //if there is only 1 element:
    if(m_size==1)
    {
        delete[] m_head;
        m_head=m_last=NULL;
    }
    //change the last the previus cell 
    else
    {
        delete m_last;
        m_last=m_last-1;
    }
    //and decrease the counter:
    m_size--;
}

现在做:

Array<int> a;
a.add(3);//work fine
a.add(4);//work fine
a.remove();//fail

我从delete m_last;行得到一个运行时错误,即使m_last点到一个实际持有数据的单元格(m_last点到一个单元格持有4)。我遗漏了什么?为什么我不能在数组中删除一个指向单元格的指针?

错误VS2012给我:_BLOCK_TYPE_IS_VAILED(pHead->nBlockUse)

我忘了说的另一件重要的事情:当调试时,它根本没有进入单元格的D'tor,它只是在删除时出来。

不能删除数组中的一个元素

int *x = new int[10];
delete &x[2] ; // It is incorrect!

你只能删除整个数组:

delete [] x;

析构函数~Cell调用delete。这是构造函数应该调用new的明确信号。