首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 其他教程 > 操作系统 >

boost:enable_shared_from_this分析

2013-02-24 
boost::enable_shared_from_this分析为什么需要boost::enable_shared_from_this?class cat{}shared_ptrc

boost::enable_shared_from_this分析
为什么需要boost::enable_shared_from_this?

class cat{};shared_ptr<cat> p(new cat);shared_ptr<cat> p2(p);class cat:public boost::enable_shared_frome_this{};shared_ptr<cat> p(new cat);shared_ptr<cat> p2=p->shared_from_this();


这两段代码看似没什么区别。但是如果你在程序里,比如在cat中的成员方法中,有的只是cat的raw pointer,但你依然想利用shared_ptr的自动delete特性,又不想自己防止由于存在多个shared_ptr<cat>对同一个cat对象delete多次的危险。即多个shared_ptr<cat>共用同一个计数器。这时候,boost::enable_shared_frome_this就变得很方便了。

struct A;void f(shared_ptr<A> const&) {...}struct A: public enable_shared_from_this<A>{    void a_f()    {        // you need to call f() here passing itself as a parameter        f(shared_from_this());    }};shared_ptr<A> a_ptr(new A());a_ptr->a_f(); // in inner call to f() will be used temporary shared_ptr<A> // that uses (shares) the same reference counter as a_ptr 


boost::enable_shared_from_this原理

其实继承了boost::enable_shared_from_this的类,真正的magic是发生在创建它的第一个shared_ptr实例时。shared_ptr会反调boost::enable_shared_from_this的_internal_accept_owner方法。
template<class T> class enable_shared_from_this{protected:    enable_shared_from_this()    {    }    enable_shared_from_this(enable_shared_from_this const &)    {    }    enable_shared_from_this & operator=(enable_shared_from_this const &)    {        return *this;    }    ~enable_shared_from_this()    {    }public:    shared_ptr<T> shared_from_this()    {        shared_ptr<T> p( weak_this_ );        BOOST_ASSERT( p.get() == this );        return p;    }    shared_ptr<T const> shared_from_this() const    {        shared_ptr<T const> p( weak_this_ );        BOOST_ASSERT( p.get() == this );        return p;    }public: // actually private, but avoids compiler template friendship issues    // Note: invoked automatically by shared_ptr; do not call    template<class X, class Y> void _internal_accept_owner( shared_ptr<X> const * ppx, Y * py ) const    {        if( weak_this_.expired() )        {            weak_this_ = shared_ptr<T>( *ppx, py );        }    }private:    mutable weak_ptr<T> weak_this_;};//从源码中,可以看出,重点不在于初始化的时候。而是在于创建第一个该对象的shared_ptr的时候:template<class Y>explicit shared_ptr( Y * p ): px( p ), pn( p ) // Y must be complete{    boost::detail::sp_enable_shared_from_this( this, p, p );}template< class X, class Y, class T > inline void sp_enable_shared_from_this( boost::shared_ptr<X> const * ppx, Y const * py, boost::enable_shared_from_this< T > const * pe ){    if( pe != 0 )    {        pe->_internal_accept_owner( ppx, const_cast< Y* >( py ) );    }}



热点排行