1

我想深拷贝一个int数组。当它通过析构函数时,我得到一个断言错误:_BLOCK_TYPE_IS_VALID(pHead->nBlockUse)。我被告知是因为它试图删除不存在的东西。请让我知道我是否走在正确的轨道上并且只需要更改一些小东西,或者我是否完全迷失了并且不知道。如果需要,我可以添加更多代码。

感谢您的回答。

。H

private:
    int* _myArray;
    int _size;
    int _capacity;

.cpp

MyVector::MyVector()
{
_myArray = new int[2];
_size = 0;
_capacity = 2;
}

MyVector::MyVector(int aSize)
{
_myArray = new int[aSize];
_size = 0;
_capacity = aSize;
}

 MyVector::~MyVector()
 {
if(_myArray != NULL)
{
    delete[] _myArray;
    _myArray = NULL;
}
 }
MyVector::MyVector(const MyVector& mVector)
{
_capacity = mVector._capacity;
_size = mVector._size;

//  if(mVector._myArray)
//  {
//  _myArray = new int[_capacity];

//  copy(mVector._myArray, mVector._myArray+_capacity, _myArray);
//  }
}

  MyVector& MyVector::operator=(MyVector& setterVect)
{
delete [] _myArray;

if(setterVect._myArray)
{
    _myArray = new int[_capacity];

    copy(setterVect._myArray, setterVect._myArray+_capacity, _myArray);
}

return *this;
}
4

1 回答 1

4

You need to make sure you are following the "Rule of Three".

Apart from copy constructor & destructor You should also provide a copy assignment operator which should do a deep copy of dynamically allocated pointer member.

On a side note, the best solution is to simply drop the dynamically allocated member and use a std::vector it saves you all the hassles of manual memory management.

于 2012-12-11T04:27:24.063 回答