Monday, October 12, 2009

c++: deleting elements from a map

Q: Does std::map.erase() properly delete pointers, or does it create memory leaks?

A: It properly does not delete pointers, because it can't assume that nothing else points at the same thing. std::map cleans up the memory *it* explicitly allocated. *You* clean up the memory *you* explicitly allocated.


Here's how to safely delete all elements in a map, that will work for any container:
std::map<int, char*> Mappy;

int main()
{
    for(int Index = 0; Index < 10; ++Index)
    Mappy.insert(std::make_pair(Index, new char[10]));

    for(std::map<int, char*>::iterator MapItor = Mappy.begin(); MapItor != Mappy.end(); ++MapItor)
    {
        char* Value = (*MapItor).second;
        delete Value;
    }

    system("pause");
    return 0;
}

No comments: