随笔 - 21  文章 - 0  trackbacks - 0
<2014年7月>
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789

常用链接

留言簿

随笔分类

随笔档案

文章分类

搜索

  •  

最新评论

阅读排行榜

评论排行榜

The header <boost/enable_shared_from_this.hpp> defines the class template enable_shared_from_this. It is used as a base class that allows a shared_ptr to the current object to be obtained from within a member function.
这个类被用作基类,提供了成员函数来获取指向当前对象的shared_ptr指针。提供了两个函数返回a shared_ptr<T> 或者 a shared_ptr<T> 。


一个很重要的原则就是一定要先有smart_ptr指向当前的对象。

下面是源码分析

从enable_shared_from_this派生的继承了下面的成员

mutable weak_ptr<T> weak_this_;

获取当前对象的shared_ptr指针就是从该weak_ptr提升而来。

    shared_ptr<T> shared_from_this()
    {
        shared_ptr<T> p( weak_this_ );
        BOOST_ASSERT( p.get() == this );
        return p;
    }

那么这个weak_ptr又是什么时候初始化的呢,根据weak_ptr的用法,是必定要从shared_ptr初始化而来,所以就得出了上面的一条重要原则,一定要先有smart_ptr指向当前的对象。

正确用法,自带例子,Y是从enable_shared_from_this派生而来的。

class Y: public boost::enable_shared_from_this<Y>
{
public:

    boost::shared_ptr<Y> f()
    {
        return shared_from_this();
    }
};




    boost::shared_ptr<Y> p(new Y);
    boost::shared_ptr<Y> q = p->f();

可能的错误用法:会抛出异常
    Y  yy;
    boost::shared_ptr<Y> q = yy.f();

因为Y的成员weak_ptr 根本就没有得到初始化。


weak_ptr的初始化

boost::shared_ptr<Y> p(new Y);

这一句执行shared_ptr的执行构造函数过程中:


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 ) );
        } 
   }


最后的enable_shared_from_this::
_interlnal_accept_owner函数中对weak_ptr完成初始化。

    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 );
        }
    }


posted on 2014-07-02 12:16 pizzx 阅读(527) 评论(0)  编辑 收藏 引用 所属分类: c++/boost

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理