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.
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.
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.
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.
In short deleting a vector of pointers without creating any memory leaks. delete *it; tckts. erase(tckts.
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With