Quote Originally Posted by rkennedy9064 View Post
I just finished building an arraylist class in c++ and was wondering if i did the add method right. I did java programming before but am new with pointers. If anyone has any time could you check out the add method of my code and tell me if you see any flaws. If i did it right then it should double the arrays size every time it fills up and then have my lits point to it.

Code:
template <class element>
void ArrayList<element>::add(const element& item)
{
    if(length == maxSize)
    {
        maxSize *= 2;
        element *temp = new element[maxSize];

        for(int i = 0; i < length; i++)
        {
            temp[i] = list[i];
        }

        delete [] list;
        list = temp;
        temp = NULL;
    }
    
    list[length] = item;
    length++;
}
If this is not an exercise, then you did it wrong. The correct way to do it would have been to use a vector.

That said, from a coding point of view, your code works, but it is not memory leak free in case of exceptions. If you have an exception before the end of the function, you will exit before having deleted temp.

There are two ways to solve this:
1 - (IMO the "bad" way): use try catch and always delete.
2 - (IMO the "good" way): Create the memory in a RAII object. For example, another ArrayList (we'll call it arrayList2). Simply fill this arrayList2, while making sure it has pre-allocated maxSize*2. Once you are done, just swap the list pointers from both objects. Your current object will be bigger, and the arrayList2 will contain the "old" data, and will be destroyed along with arrayList2 on leaving the method. If there is ANYTHING that goes wrong, and you prematurely exit, rest assured that ArrayList's destructor will be doing the cleanup. Another advantage is this gives you a "strong" exception safety. Basically, you are guaranteeing that should an exception occur, your *this object will not be modified.