I am trying to develop a generic List with templates. This list is compound by a Pointer array T* , an integer for getting the number of elements and some methods( find, contains…) It´s important to say that I cannot use std::library.
My problem comes when I am working with a List<List<int> > for instance.
One of the methods make a resizing of the T* pointer array, So when I have this List<List>>I create an auxpointer of a bigger size than T* and copying T content to auxpointer with a memcpy. The inner Pointers (list.T.T) are copied as pointers too, not memory duplicated, so when I delete the T* pointer and reasign T=auxpointer. I have already lost the data of that pointers in my new T.
template <typename T>
void CGenericList<T>::resize()
{
T* auxPointer = new T[this->maxElements*2];
memcpy (auxPointer,this->pointer,this->maxElements*sizeof(T));
delete[] this->pointer;
this->pointer=auxPointer;
this->maxElements=2*this->maxElements;
}
template<class T>
class CGenericList
{
public:
T* pointer;
int N;
int maxElements;
CGenericList();
CGenericList(int);
~CGenericList();
void resize();
}
Can anyone give me any tips for doing it?
The code you posted shows some problems.
here you allocate a new array of maxElements*2 – and call the default constructor.
Which in your case probably initialises all Listelements.
After that you copy the content of your old array to the memory area of the newly allocated memory. This overwrites the pointers to the just created Listelements with the ones from the old array -> memory leak.
Then you delete the array, this calls the destructors of all elements.
Which hopefully will delete their content and free their memory.
Finally you reassign the newly created array. The pointers in the list point to the old listselements and point to not allocated memory anymore (because of the call to the destructor via delete[]).
A solution would be to implement an copy constructor for your list and call it for all
elements in your array. (DeepCopy) And of course an assignment operator, i almost forgot 😉
Probably somethig like this – be aware that this is “asis” and definitely not exceptionsafe 😉
If you don’t like to use stl you can have a look at stlport