Kam
Kam

Reputation: 6008

Memory Leak in a list of pointers to objects

I have a list of pointers to objects.

 std::list<X*> xList;

All I need is the size of the list so my method, populates this list and calls size() on it and then returns the size.

NOTE: I know this is not the best solution, but I am using an API that provides a list with dynamically allocated objects and this is the only way I can do it.

Now valgrind is saying that there's memory leaks here. I am assuming that this is because I never delete the objects that are in the list.

I thought I'll do this:

std::list<X*>::iterator iter;
for (iter = xList.begin(); iter != xList.end(); ++iter)
{
    delete (*iter);
}

but is this the best solution to this?

Upvotes: 1

Views: 785

Answers (2)

Puppy
Puppy

Reputation: 146910

No, the best solution would be to have a std::list<std::unique_ptr<X>> instead. Now the objects will delete themselves as and when it's appropriate, and you do not have to concern yourself with it. When the std::list is destroyed, the X objects which are owned by it are also destroyed.

Upvotes: 6

Luchian Grigore
Luchian Grigore

Reputation: 258548

but is this the best solution to this?

No, the best solution would be to have a std::list<std::shared_ptr<X> > instead.

Upvotes: 2

Related Questions