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

I am debugging one memory issue, it has something to do with the method std::list::erase

.

While reading the documentation for, std::list::erase

I saw this statement :

"This effectively reduces the size of the container by the number of deleted items that are destroyed."

This statement is difficult for me to understand. As an example, consider this setting:

class demo {

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

      

Now let's say what I call mylist.erase(iterator of list)

. I thought this would call the destructor for the class demo

, but it doesn't seem to contradict the "which are destroyed" statement.

Could you help me with this?

Thank!

+3


source to share


1 answer


When you call the clear()

list method , it will destroy all objects stored inside the list. In your case, you have a list demo*

This means that every pointer will be destroyed since the pointers are stored inside the list, but the pointers will not be destroyed because the pointers will not be stored in the list.In other words, destroying pointers is not the same as calling delete

for each of these pointers. As a result, it is generally not a good idea to store original pointers in container types if those pointers own the objects they point to, because, as you just saw, destructors are not automatically called.

Now, on the other hand, suppose you have list<unique_ptr<demo>>

. In this case, the call will clear()

destroy everything unique_ptr<demo>

in the list. This, in turn, will free the objects it points to unique_ptr

, since destroying a unique_ptr

also destroys the object it points to. It works because it unique_ptr

has the idea of ​​ownership and realizes that it needs to destroy the object it points to when it itself is destroyed.



Hope this helps!

+3


source







All Articles