简体   繁体   中英

Delete memory of std::map<int, string> completely

I have a map filled with and now I want to delete the memory completely. How do I do this right? couldn't find anything specific for this topic, sorry if it is already answered...

my code is something like this:

      for(std::map<short,std::string>::iterator ii=map.begin();   
ii!=map.end(); ++ii)
    {
        delete &ii;
    }

But it doesnt work. Can anybody help pls?

regards, phil

The way to do it right is not to do it. A map will automatically release resources when it's destroyed for anything allocated automatically.

Unless you allocated the values with new , you don't delete them.

{
    std::map<short,std::string> x;
    x[0] = "str";
}
//no leaks here

{
    std::map<short,std::string*> x;
    x[0] = new std::string;  
    delete x[0];
}

Simply call map.clear(); . This will release all objects the map has allocated internally.

Note that in system tools like the task manager, your application can still show the same amount of memory occupied. It's perfectly possible the OS decides not to reclaim the memory your process once held, in case it allocated it again. It would reclaim it later if it started to run short.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM