0

I have made for school purposes my own take on a dynamically allocated array using templates.

While what I'm about to ask works, I don't know how and why and I've reached the point where I need to know.

template <typename TElement>
DynamicArray<TElement>::ensureCapacity () {
    if (capacity >= elemNumb) {
        return; //we have space to store the values
    }
    //we need to allocate more space for the values
    TElement *auxArray = myArray;
    //create space to hold more numbers
    capacity = capacity * 2;
    myArray = new TElement[capacity];
    //copy the values
    for (int i = 0; i < size; i++) {
        myArray[i] = auxArray[i];
    }
    //release the memory
    delete[] auxArray;
}

I need to know: TElement *auxArray = myArray; How does this work ? is it using pointers, are elements copied one by one ? I need to understand how it works so that I can figure out the complexity of my algorithm. I don't mind if some one tells me the complexity but the real answer I'm looking for is how does that work ?

Also myArray = new TElement[capacity]; I do this before deleting the old myArray does this delete the old one ? or is it still floating somewhere in memory in one form or another ?

Kalec
  • 2,681
  • 9
  • 30
  • 49
  • 4
    To clarify; you're saying that you wrote this code, but that you don't know how any of it works? – Oliver Charlesworth Jun 10 '12 at 16:52
  • @OliCharlesworth Well ofc. C++ is very complex. I do not have a complete understanding of it. I can easily do stupid stuff like Creating 500 dynamically allocated arrays and without de-allocating them and flowing trough memory but me having no idea because 500 * 10 int is not that much ram (0.019 mb). I cold not notice that even if it was the difference between life and death. – Kalec Jun 10 '12 at 16:54
  • 1
    It is essential to understand all that stuff, but in real code you should favour using smart pointers over raw pointers to dynamically allocated objects. Have a look at [C++11 smart pointers](http://en.wikipedia.org/wiki/Smart_pointer) – juanchopanza Jun 10 '12 at 17:24

1 Answers1

2

This

TElement *auxArray = myArray;

just means that auxArray points to whatever myArray is pointing to. There is no copying of anything else, it is just a pointer copy.

This

myArray = new TElement[capacity];

means that myArray now points to a new, dynamically allocated TElement array. The expression doesn't delete anything. But auxArray is pointing to what myArray was pointing before this assignment, so when you delete auxArray, you release the resources originally pointed to by myArray.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480