码迷,mamicode.com
首页 > 其他好文 > 详细

map的erase()释放内存

时间:2015-07-09 13:05:32      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:

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

 1 #include <iostream>
 2 #include <map>
 3 #include <string>
 4 
 5 using  namespace std;
 6 struct value{
 7     int i;
 8     std::string test;
 9 };
10 
11 int main()
12 {
13     std::map<int, value*> test_map;
14     for(int i=0; i<10; ++i){
15         value* tmp = new value();
16         tmp->i = i;
17         tmp->test = "test";
18         test_map.insert(make_pair(i, tmp));
19     }   
20 
21     for(std::map<int, value*>::iterator it=test_map.begin(); it!=test_map.end();){
22         std::cout << "first " << it->first << " second " << (it->second)->i <<" "<< (it->second)->test << std::endl;
23         delete it->second;
24         it->second = NULL;
25         //test_map.erase(it);     //迭代器失效;
26         test_map.erase(it++);   //防止迭代器失效,切记、切记
27     }   
28    /*  常见错误
21     for(std::map<int, value*>::iterator it=test_map.begin(); it!=test_map.end(); ++it){
22         std::cout << "first " << it->first << " second " << (it->second)->i <<" "<< (it->second)->test << std::endl;
23         delete it->second;
24         it->second = NULL;
25         test_map.erase(it);     //迭代器失效;
26         //erase掉iterator指向的内容,该iterator直接失效,下次循环里面的++it等任何操作其结果都是未定义的。使用valgrind可以检测到错误:Invalid read of size 8
27     }  
*/
29     return 0;
30 }
31 
32 root@u18:~/cp/test# g++ map3.cpp  -g -Wall
33 root@u18:~/cp/test# ls -lt a.out
34 -rwxr-xr-x 1 root root 87224 Jul  9 11:00 a.out
35 root@u18:~/cp/test# valgrind  --tool=memcheck  --leak-check=full ./a.out
36 ==28426== Memcheck, a memory error detector
37 ==28426== Copyright (C) 2002-2011, and GNU GPLd, by Julian Seward et al.
38 ==28426== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
39 ==28426== Command: ./a.out
40 ==28426== 
41 first 0 second 0 test
42 first 1 second 1 test
43 first 2 second 2 test
44 first 3 second 3 test
45 first 4 second 4 test
46 first 5 second 5 test
47 first 6 second 6 test
48 first 7 second 7 test
49 first 8 second 8 test
50 first 9 second 9 test
51 ==28426== 
52 ==28426== HEAP SUMMARY:
53 ==28426==     in use at exit: 0 bytes in 0 blocks
54 ==28426==   total heap usage: 30 allocs, 30 frees, 930 bytes allocated
55 ==28426== 
56 ==28426== All heap blocks were freed -- no leaks are possible
57 ==28426== 
58 ==28426== For counts of detected and suppressed errors, rerun with: -v
59 ==28426== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)

 

map的erase()释放内存

标签:

原文地址:http://www.cnblogs.com/chris-cp/p/4632565.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!