首页 技术 正文
技术 2022年11月12日
0 收藏 897 点赞 2,689 浏览 1280 个字

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

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,026
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,516
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,364
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,145
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,778
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,856