Jee Jee - 4 months ago 14
C++ Question

Deleting new'd memory in a std::map?

Say I have a map of pointers that I

new
, how can I iterate through this map and delete them cleanly? What I've tried doesn't seem to work:

std::map<std::string, Foo*> foos;
foos.insert(std::make_pair("blah", new Foo()));

for (auto& f : foos) {
delete f;
}

Answer

A std::map contains key-values pairs. Thus when you do

for (auto& f : foos) {
    delete f;
}

f is a pair and not the pointer that you stored in the map. You cannot call delete on that pair as you did not allocate it. If you wan to delete all of the pointers in the map then you can use

for (auto& f : foos) {
    delete f.second;
}
foos.clear();

This will delete every pointer in the map and then the clear() call will empty the map so you do not have a map full of deleted pointers.

I do suggest though that you use plain values if you can and if not then at least use smart pointers. They will handle the memory deallocation for you.