您的位置:首页 > 其它

map的erase()释放内存

2015-07-09 11:08 369 查看
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=0; i<10; ++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 0;
}

root@u18:~/cp/test# g++ map3.cpp  -g -Wall
root@u18:~/cp/test# ls -lt a.out
-rwxr-xr-x 1 root root 87224 Jul  9 11:00 a.out
root@u18:~/cp/test# valgrind  --tool=memcheck  --leak-check=full ./a.out
==28426== Memcheck, a memory error detector
==28426== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.
==28426== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
==28426== Command: ./a.out
==28426==
first 0 second 0 test
first 1 second 1 test
first 2 second 2 test
first 3 second 3 test
first 4 second 4 test
first 5 second 5 test
first 6 second 6 test
first 7 second 7 test
first 8 second 8 test
first 9 second 9 test
==28426==
==28426== HEAP SUMMARY:
==28426==     in use at exit: 0 bytes in 0 blocks
==28426==   total heap usage: 30 allocs, 30 frees, 930 bytes allocated
==28426==
==28426== All heap blocks were freed -- no leaks are possible
==28426==
==28426== For counts of detected and suppressed errors, rerun with: -v
==28426== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: