Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cleaning up an STL list/vector of pointers

Tags:

c++

list

stl

vector

What is the shortest chunk of C++ you can come up with to safely clean up a std::vector or std::list of pointers? (assuming you have to call delete on the pointers?)

list<Foo*> foo_list; 

I'd rather not use Boost or wrap my pointers with smart pointers.

like image 680
twk Avatar asked Nov 20 '08 22:11

twk


People also ask

How do you clean a vector pointer?

Another solution is to delete the pointers to remove and set them to nullptr and only then perform a std::remove on nullptr : for(auto& pointer : vec) { if (*pointer % 2 == 0) { delete pointer; pointer = nullptr; } } vec. erase(std::remove(vec. begin(), vec.

Does a vector of pointers need to be deleted?

Yes, the code has a memory leak unless you delete the pointers. If the foo class owns the pointers, it is its responsibility to delete them. You should do this before clearing the vector, otherwise you lose the handle to the memory you need to de-allocate.

How do I delete a STL list?

list::clear() is an inbuilt function in C++ STL which is declared in header file. list::clear(), clears the whole list. In other words the clear() removes all the elements present in the list container and leaves the container with size 0.

How do you clear a vector of a pointer in C++?

In short deleting a vector of pointers without creating any memory leaks. delete *it; tckts. erase(tckts.


1 Answers

For std::list<T*> use:

while(!foo.empty()) delete foo.front(), foo.pop_front(); 

For std::vector<T*> use:

while(!bar.empty()) delete bar.back(), bar.pop_back(); 

Not sure why i took front instead of back for std::list above. I guess it's the feeling that it's faster. But actually both are constant time :). Anyway wrap it into a function and have fun:

template<typename Container> void delete_them(Container& c) { while(!c.empty()) delete c.back(), c.pop_back(); } 
like image 113
Johannes Schaub - litb Avatar answered Sep 22 '22 17:09

Johannes Schaub - litb