读书人

多个非同源的shared_ptr管理对象唤起d

发布时间: 2013-10-29 12:07:57 作者: rapoo

多个非同源的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 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();    return 0;}

程序输出:

show()
~test

读书人网 >编程

热点推荐