清除vector中的非smartpointer
来源:互联网 发布:mysql emoji 截断 编辑:程序博客网 时间:2024/06/08 05:11
容器一大坑,对放入的指针没有所有权。如果用户不自己释放,将引起内存泄漏。
例程如下:
class Counted { int id; static int count; public: Counted() :id(count++) { cout << "Counted id = " << id << ends; cout << " it's created" << endl; }; ~Counted() { cout << "Counted id = " << id << ends; cout << " it's destroyed" << endl; } }; int Counted::count = 1;
丑陋的版本
vector<Counted*>v_co; for (int i = 0; i < 20; i++) { v_co.push_back(new Counted()); } vector<Counted*>::iterator it = v_co.end(); --it; while (it >= v_co.begin()) { delete *it; if (it != v_co.begin()) it--; else break; } v_co.clear(); cout << v_co.size() << endl;
这里用rbegin() 与 rend()会优雅点,另外这两个迭代器属于不同的类型。
auto it = v_co.rbegin(); while (it != v_co.rend()) { delete *it; it++; } v_co.clear(); cout << v_co.size() << endl;
阅读全文
0 0
- 清除vector中的非smartpointer
- smartPointer
- SmartPointer
- SmartPointer
- 清除 C++ vector 中的冗余元素
- android smartpointer
- vector清除操作
- vector容器内存清除测试
- 6.Boost之smartpointer
- 验证数字清除非数字
- 用swap清除vector,deque内存
- 快速清除STL::vector的内存
- 用swap清除vector,deque内存
- vector中清除某个元素方法(erase)
- vector删除元素与清除内存空洞
- 深度探索智能指针(SmartPointer)
- 清除电脑中的垃圾
- 清除select中的options
- easyui datagrid动态修改url
- 关于margin重叠现象的解决方案
- Mysql中模糊查询的四种用法介绍
- java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener!
- LinkedBlockingQueue与ArrayBlockingQueue性能比较
- 清除vector中的非smartpointer
- RxJava+Retrofit+OkHttp深入浅出-终极封装七(异常处理)
- RxJava+Retrofit+OkHttp深入浅出-mvp(使用篇)
- eclipse使用技巧快捷键大全
- Android App 沉浸式状态栏解决方案
- ubuntu下允许root用户ssh远程登录
- struts2核心工作原理
- Retrofit源码解析-动态代理
- Ubuntu14.04+ROS Indigo+SVO(Semi-direct Visual Odometry)