创建this的智能指针

来源:互联网 发布:上海开网络叫车 编辑:程序博客网 时间:2024/06/06 02:02

今天调试的时候发现了一个BUG:A对象的Func(),在调用第二次的时候就崩溃了。

单步发现第二次调用之前,A对象已经被析构。再向前找,发现在Func()内部创建了一个指向this的智能指针p:“boost::shared_ptr<A> p(this)”,这是完全错误的用法。

由于在Func()出栈的时候p的ref count就已经没有了,boost会帮我delete掉this,而这明显不是我所期望的。


其实boost提供了专门为this设计的shared_ptr,用法如下(抄自网络):


#include <boost/enable_shared_from_this.hpp>class Y: public boost::enable_shared_from_this<Y>{public:    shared_ptr<Y> f()    {        return shared_from_this();    }}int main(){    shared_ptr<Y> p(new Y);    shared_ptr<Y> q = p->f();    assert(p == q);    assert(!(p < q || q < p)); // p and q must share ownership}

需要this智能指针时,把该类继承于publicboost::enable_shared_from_this<T>,然后在需要shared_ptr的地方调用shared_from_this()。

源于: http://stackoverflow.com/questions/11711034/stdshared-ptr-of-this

http://stackoverflow.com/questions/142391/getting-a-boostshared-ptr-for-this

0 0
原创粉丝点击