【发布时间】:2012-12-11 04:20:37
【问题描述】:
我想深拷贝一个 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;
}
【问题讨论】:
-
你是否在默认构造函数中将
_myArray初始化为NULL? -
不,我只是从我的构造函数中添加了代码。我将其设置为 2。
-
不久前,我写了一篇blog post,关于您可能会感兴趣的动态数组。
标签: c++ arrays memory-leaks deep-copy