64,651
社区成员
发帖
与我相关
我的任务
分享
template<class Y>
explicit shared_ptr( Y * p ): px( p ), pn() // px是被管理的对象指针;pn是引用计数器,shared_ptr内部管理
{
boost::detail::sp_pointer_construct( this, p, pn ); // 开始构造
}
template< class T, class Y > inline void sp_pointer_construct( boost::shared_ptr< T > * ppx, Y * p, boost::detail::shared_count & pn )
{
boost::detail::shared_count( p ).swap( pn ); // 创建引用计数器,swap等价于赋值给pn
boost::detail::sp_enable_shared_from_this( ppx, p, p );
}
// sp_enable_shared_from_this 模板重载了多个,针对被管理的是enable_shared_from_this的派生类的对象时自动选择执行这个函数
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 T> class enable_shared_from_this
{
public:
// 获取指向自身的智能指针,weak_ptr作为观察者能够判断指针是否已经释放
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:
// 派生对象内部保存一份私有的weak_ptr,用来获取指向自身(this)的智能指针
// 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_;
};