Question

I was trying to program my own List class on C++.

Here is the code:

template <class T>
class List
{
private:
    T *value, *valueHelper;
    int valueSize;

public:
    int size;

List()
{
    valueSize = 2;
    value = new T[valueSize];
    size = 0;
}


void Add(T val)
{
    size++;

    if (size > valueSize)
    {
        valueSize *= 2;
        valueHelper = new T[valueSize]; 

        memcpy(valueHelper, value, sizeof(T) * (size - 1));

        delete[](value);
        value = valueHelper;
    }

    value[size - 1] = val;

}


void Clear()
{
    delete[](value);
    size = 0;
    valueSize = 2;
    value = new T[valueSize];
}


T & operator[](int P)
{
    return value[P];
}

};

The problem appered when I used a class variable on this List Class. When I do Clear to delete some memory, there are a run time error appers.

I have trying to check what cause this problem and I have find out that this line on the function Clear() is the error line:

delete[](value);

I can not understand, why?

Was it helpful?

Solution

I'm just guessing here, but it could be likely it is because you will have copies made of the List instance, for example by returning it from a function or passing it as a non-reference argument to a function.

Copying of objects are implemented by the default copy-constructor generated by the compiler, but it only does shallow copying, meaning it will copy the pointers but not what they point to. So then you will have two copies with pointers pointing to the same memory, and when one object deletes that memory the others pointer will be invalid.

You also have a memory leak in that you don't have a destructor, so when an instance goes out of scope then you loose the allocated memory forever.

You should also read about the rule of three.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top