Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

map

stl

free

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

like image 545
skylla Avatar asked Apr 10 '13 11:04

skylla


People also ask

How do you clear a STD map in C++?

clear() function is used to remove all the elements from the map container and thus leaving it's size 0. Syntax: map1. clear() where map1 is the name of the map.

Does map clear free memory C++?

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.

How do you delete a STD map?

You can simply call myMap. clear() to delete myMap 's content.

Does map erase deallocate memory?

No it doesn't free the memory if it is a naked pointer. You need to ensure that the memory is deallocated appropriately.


1 Answers

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];
}
like image 128
Luchian Grigore Avatar answered Oct 28 '22 09:10

Luchian Grigore