0

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

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++;
}

这是删除的实现:

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)

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

4

2 回答 2

3

您不能删除数组的一个元素。

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

您只能删除整个数组:

delete [] x;
于 2013-06-08T08:18:44.057 回答
2

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

于 2013-06-08T08:16:20.950 回答