user6245072 user6245072 - 1 month ago 7
C++ Question

Deleting content of a std::list

I have a list of pointers which I don't need anymore. To delete all of them, I can normally iterate the list:

for (T* ptr: mylist) {
delete ptr;
}


Or I can delete the first or last element until the list is empty:

while (!mylist.empty()) {
delete mylist.front(); //or mylist.back()
mylist.pop_front(); //or mylist.pop_back()
}


What is the preferred way, both for performance and clarity?

Answer

The best way is to store std::unique_ptr's in list and not manage memory yourself. Then you just do mylist.clear().