boost::enable_shared_from_this分析

[color=red][size=medium]为什么需要boost::enable_shared_from_this?[/size][/color]


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


[color=red][size=medium]boost::enable_shared_from_this原理[/size][/color]

其实继承了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 ) );
}
}


[color=white]作者:翁志艺[/color]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值