ivanseidel/LinkedList

Clear() vs Remove

iisfaq opened this issue · 1 comments

Thanks for the library - it is great.

A quick tip though (maybe useful to put into the readme) is that using clear() can be dangerous to use if you are using a class as the list data compared to a int for example.

The reason is that if you dynamically create your class such as in your ClassList example

Animal *dog = new Animal();
dog->name = dogname;
dog->isMammal = true;

When you use the clear() method the 'dog' object is not freed up and consumes memory.

A better approach when using a class for the list data is like this

while (myAnimalList.size() > 0)
{
delete myAnimalList.remove(0);
}

This then frees up the dynamic object as it is removed from the list.

This may help someone who is adding/deleting objects at runtime.

Chris

Fixed @iisfaq ! Thanks for the suggestion...