SirRupertIII
SirRupertIII

Reputation: 12595

Deep copy int array c++

I want to deep copy an array of int. I get an Assertion Error: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse) when it goes through the destructor. Which I've been told is because It's trying to delete something that is not there. Please let me know if I am on the right track and just need to change something small, or if I am completely lost and don't know it. I can add more code if needed.

Thanks for the answers.

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

Upvotes: 1

Views: 4276

Answers (1)

Alok Save
Alok Save

Reputation: 206566

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.

Upvotes: 4

Related Questions