map的erase()释放内存

时间:2021-05-08 05:27:24

STL中的map调用erase(it),当value值为指针时,释放内存:

 #include <iostream>
#include <map>
#include <string> using namespace std;
struct value{
int i;
std::string test;
}; int main()
{
std::map<int, value*> test_map;
for(int i=; i<; ++i){
value* tmp = new value();
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();){
std::cout << "first " << it->first << " second " << (it->second)->i <<" "<< (it->second)->test << std::endl;
delete it->second;
it->second = NULL;
//test_map.erase(it); //迭代器失效;
test_map.erase(it++); //防止迭代器失效,切记、切记
} return ;
} root@u18:~/cp/test# g++ map3.cpp -g -Wall
root@u18:~/cp/test# ls -lt a.out
-rwxr-xr-x root root Jul : a.out
root@u18:~/cp/test# valgrind --tool=memcheck --leak-check=full ./a.out
==== Memcheck, a memory error detector
==== Copyright (C) -, and GNU GPL'd, by Julian Seward et al.
==== Using Valgrind-3.7. and LibVEX; rerun with -h for copyright info
==== Command: ./a.out
====
first second test
first second test
first second test
first second test
first second test
first second test
first second test
first second test
first second test
first second test
====
==== HEAP SUMMARY:
==== in use at exit: bytes in blocks
==== total heap usage: allocs, frees, bytes allocated
====
==== All heap blocks were freed -- no leaks are possible
====
==== For counts of detected and suppressed errors, rerun with: -v
==== ERROR SUMMARY: errors from contexts (suppressed: from )