您好,欢迎来到爱够旅游网。
搜索
您的当前位置:首页map的erase()释放内存

map的erase()释放内存

来源:爱够旅游网
map的erase()释放内存

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

1 #include 2 #include 3 #include 4

5 using namespace std; 6 struct value{ 7 int i;

8 std::string test; 9 };10

11 int main()12 {

13 std::map 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::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

29 return 0;30 }31

32 root@u18:~/cp/test# g++ map3.cpp -g -Wall33 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.out36 ==28426== Memcheck, a memory error detector

37 ==28426== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.38 ==28426== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info39 ==28426== Command: ./a.out40 ==28426==

41 first 0 second 0 test42 first 1 second 1 test43 first 2 second 2 test44 first 3 second 3 test45 first 4 second 4 test46 first 5 second 5 test47 first 6 second 6 test48 first 7 second 7 test49 first 8 second 8 test50 first 9 second 9 test51 ==28426==

52 ==28426== HEAP SUMMARY:

53 ==28426== in use at exit: 0 bytes in 0 blocks

==28426== total heap usage: 30 allocs, 30 frees, 930 bytes allocated55 ==28426==

56 ==28426== All heap blocks were freed -- no leaks are possible57 ==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)

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- igbc.cn 版权所有 湘ICP备2023023988号-5

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务