多个非同源的shared_ptr管理对象引起double free
来源:互联网 发布:淘宝默认好评图 编辑:程序博客网 时间:2024/04/27 14:08
有多个不同源的shared_ptr管理对象时会出现多次释放对象,这里不同源是指多组间不是通过拷贝构造、复制等手段而来的,即几组shared_ptr是独立声明的。
#include<iostream>#include<pthread.h>#include<unistd.h>#include<boost/enable_shared_from_this.hpp>#include<boost/shared_ptr.hpp>using namespace std;using namespace boost;class test{ public: void show(){ shared_ptr<test> one(this);//###1###带此符号的两处shared_ptr非同源会造成:这里的shared_ptr退出作用后就将管理的对象进行析构,而外层的shared_ptr对此全然不知,继续使用该对象,麻烦就来了... cout<<"show()"<<endl; } ~test(){ cout<<"~test"<<endl; }};int main(){ shared_ptr<test> one(new test);//###1### one->show(); shared_ptr<test> two=one;//拷贝一个shared_ptr two->show(); return 0;}
程序输出:
show()
~test
show()
~test //同一对象析构了两次
*** glibc detected *** ./two_shared_ptr_1: double free or corruption (fasttop): 0x000000000080b010 *** //double free
采用继承enable_shared_from_this,然后使用shared_from_this()可以解决这个问题
#include<iostream>#include<pthread.h>#include<unistd.h>#include<boost/enable_shared_from_this.hpp>#include<boost/shared_ptr.hpp>using namespace std;using namespace boost;class test:public enable_shared_from_this<test> {//继承 public: void show(){ shared_ptr<test> one(shared_from_this());//采用shared_from_this()的shared_ptr是同源的 cout<<"show()"<<endl; } ~test(){ cout<<"~test"<<endl; }};int main(){ shared_ptr<test> one(new test); one->show(); shared_ptr<test> two=one; two->show(); return 0;}
程序输出:
show()
show()
~test //正常析构
- 多个非同源的shared_ptr管理对象引起double free
- shared_ptr的错误free(): invalid pointer
- double误差引起的缺陷
- double free
- double free
- double free
- double free
- 以对象管理资源------auto_ptr shared_ptr
- 以对象管理资源 auto_ptr和shared_ptr
- 基本数据类型double和封装类型Double引起的bug
- 关于double free的一点点思考
- iOS double free 重复释放的解决方案
- weak_ptr解决shared_ptr环状引用所引起的内存泄漏
- weak_ptr解决shared_ptr环状引用所引起的内存泄漏
- weak_ptr解决shared_ptr环状引用所引起的内存泄漏
- 从unique_ptr赋值到shared_ptr引起的指针悬空bug
- weak_ptr解决shared_ptr环状引用所引起的内存泄漏
- Linux多线程服务器编程shared_ptr以及weak_ptr实现的弱回调以及对象池管理
- destoon二次开发
- 大卫谈学习3:方法还是问题,这是个问题!
- Android 根据屏幕大小设置字体大小
- 大卫谈学习4:为何你会一年经验用十年?
- CAP理论十二年回顾:"规则"变了
- 多个非同源的shared_ptr管理对象引起double free
- 程序员是“逻辑人”
- (字符串的处理4.7.16)POJ 1159 Palindrome(让一个字符串变成回文串需要插入多少个字符...先逆序,在减去公共子序列的最大长度即可)
- volatile的使用
- 第16章
- Java线程的生命周期
- A. Dima and Continuous Line
- JDBC保存EXCEL数据到数据库(2.数据表,Excel文件及javaBean准备)
- java.lang.OutOfMemoryError: Java heap space错误及处理办法(收集整理、转)