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)
相关文章推荐
- SAPUI5-Button
- CSRF(跨站请求伪造)详细说明
- linux上SVN解决冲突的办法
- HTML 5 拖放
- table checked row
- 《牛人博客汇总》
- Redis 分布式锁实现
- Wordpress使用"function_exists();"函数以提高主题兼容性
- UINavigationBar功能实现
- 关于java中的批注@SuppressWarnings
- 【LeetCode 144_二叉树_遍历】Binary Tree Preorder Traversal
- linux网络协议栈:邻居子系统
- squid完全攻略(一)squid优化后详细安装步骤
- Hyper-V下安装linux没有网卡的解决方法
- CvMemStorage
- NYOJ 62 笨小熊
- C语言中如何将二维数组作为函数的参数传递
- 网页版双色球号码生成工具
- 批处理经典入门教程!(从不懂到高手)第2/5页
- HelloWorld by Thrift