1

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;
}
SirRupertIII
  • 12,324
  • 20
  • 72
  • 121

1 Answers1

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.

Community
  • 1
  • 1
Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • okay, yeah I realize it'd be better just to use std::vector. I'm just trying to learn the whole concept of memory allocation and pointers etc. in C++. – SirRupertIII Dec 11 '12 at 04:32
  • When does the assignment operator get called and when does the copy constructor get called? I just added an assignment operator. Is that what I should be doing with it? – SirRupertIII Dec 11 '12 at 04:52
  • 1
    Here's a good [article](http://171.64.64.250/class/cs193d/handouts/14CopyConstructors.pdf) explaining when assignment operator and copy constructor are called. – Bejmax Dec 11 '12 at 05:16