多个非同源的shared_ptr管理对象引起double free

   有多个不同源的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            //正常析构

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值