The map in the STL calls Erase (IT), and when the value is a pointer, the memory is freed:
1#include <iostream>2#include <map>3#include <string>4 5 using namespacestd;6 structvalue{7 inti;8STD::stringtest;9 };Ten One intMain () A { -std::map<int, value*>Test_map; - for(intI=0; i<Ten; ++i) { thevalue* tmp =Newvalue (); -Tmp->i =i; -Tmp->test ="Test"; - Test_map.insert (Make_pair (i, TMP)); + } - + for(std::map<int, Value*>::iterator It=test_map.begin (); it!=test_map.end ();) { AStd::cout <<" First"<< It->first <<"Second"<< (it->second)->i <<" "<< (it->second)->test <<Std::endl; at DeleteIt->second; -It->second =NULL; - //test_map.erase (IT); Iterator invalidation; - test_map.erase (it++); Prevent iterators from failing, remember and remember - } 28/* Common Errors
for (Std::map<int, Value*>::iterator it=test_map.begin (); it!=test_map.end (); ++it) { std:: cout << "First" << It->first << "Second" << (it->second)->i << "" << (IT-&G T;second)->test << std::endl;23 Delete it->second;24 it->second = null;25 Test_map.erase (it); The iterator fails , and//erase iterator points to the content, the iterator direct invalidation, the next loop inside the ++it and so on any operation its results are undefined. Errors can be detected using Valgrind: Invalid read of size 8 }
*/
in return 0; - } to +[Email protected]:~/cp/test# g++ map3.cpp-g-Wall -[Email protected]:~/cp/test# ls-lt A. out the-rwxr-xr-x1Root root87224Jul9 One:xxA. out *[Email protected]:~/cp/test# valgrind--tool=memcheck--leak-check=full./A. out $==28426==Memcheck, a memory error detectorPanax Notoginseng==28426Copyright (C)2002- ., and GNU GPL'd, by Julian Seward et al. -==28426= = Using valgrind-3.7.0and Libvex; Rerun With-h forCopyright Info the==28426= = Command:./A. out +==28426== AFirst0Second0Test theFirst1Second1Test +First2Second2Test -First3Second3Test $First4Second4Test $First5Second5Test -First6Second6Test -First7Second7Test theFirst8Second8Test -First9Second9TestWuyi==28426== the==28426==HEAP SUMMARY: -==28426==inchUse at exit:0bytesinch 0blocks Wu==28426= = Total Heap Usage: -Allocs, -Frees,930Bytes Allocated -==28426== About==28426= = All heap blocks were freed--no leaks is possible $==28426== -==28426= = Counts of detected and suppressed errors, rerun with:-v -==28426= = ERROR SUMMARY:0Errors from 0Contexts (suppressed:2 from 2)
Map's erase () frees memory