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

これは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

m_last が実際にデータを保持するセルを指しているにもかかわらず、行から実行時エラーが発生しdelete m_last;ます (セルへの m_last ポイントは 4 を保持します)。ここで何が欠けていますか?配列内のセルへのポインターを削除できないのはなぜですか?

エラーVS2012は私に与えます:_BLOCK_TYPE_IS_VAILED(pHead->nBlockUse)

私が言うのを忘れていたもう一つの重要なこと: デバッグがセルの D'tor に入らないとき、それは削除に行くときだけ出ます。

4

2 に答える 2