Boost shared_from_this用法

本文详细解析了Boost库中的enable_shared_from_this类模板,包括其内部实现原理及正确使用方式。通过示例对比了正确与错误的使用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <boost/enable_shared_from_this.hpp> 

该头文件定义了一个类模板enable_shared_from_this。它是一个基类,允许继承该类的对象的成员函数在其内部获取share_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的则是在构造的时候初始化的

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

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

boost::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的成员weak_ptr 根本就没有得到初始化
Y  yy;
boost::shared_ptr<Y> q = yy.f();

 

转载于:https://my.oschina.net/shou1156226/blog/781312

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值