eswaat
eswaat

Reputation: 763

Does std::list's erase member function call the destructor for all stored elements?

I am debugging one memory issue it has some relation with the std::list::erase method.

While reading the documentation for std::list::erase, I saw this statement:

"This effectively reduces the container size by the number of elements removed, which are destroyed."

I am having difficulty in understanding this statement. As an example, consider this setup:

class demo {

};
std::list<demo *> mylist;

Now, suppose I call mylist.erase(iterator of list). I thought that this would call the destructor for class demo, but it doesn't seem to, which seems to contradict the statement "which are destroyed."

Can you please help me with this?

Thanks!

Upvotes: 3

Views: 3714

Answers (2)

A Lundgren
A Lundgren

Reputation: 23

And just to clarify, erase() also destroys the element in the same way that clear() does.

// Removes the element from the list and destroys it:
mylist.erase(iterator);

Upvotes: 0

templatetypedef
templatetypedef

Reputation: 372694

When you call the clear() method of the list, it will destroy all of the objects stored inside of the list. In your case, you have a list of demo*s This means that each of the pointers will be destroyed, since the pointers are stored inside the list, but the pointees won't be destroyed because the pointees aren't stored inside the list. In other words, destroying the pointers isn't the same as calling delete on each of those pointers. As a result, it's usually not recommended to store raw pointers in container types if those pointers own the objects they point at, since, as you've just seen, the destructors aren't called automatically.

Now, on the other hand, suppose you have a list<unique_ptr<demo>>. In that case, calling clear() will destroy all the unique_ptr<demo>s in the list. This in turn will deallocate the objects that the unique_ptrs point at, since destroying a unique_ptr also destroys the object it points at. This works because unique_ptr has an idea of ownership and realizes that it needs to destroy the object it points at when it is itself destroyed.

Hope this helps!

Upvotes: 4

Related Questions