boost中的shared_ptr的问题

__Cm_duck 2014-08-28 10:22:56
#include <iostream>
using namespace std;

class D: public boost::enable_shared_from_this<D>
{
public:
D()
{
cout<<"D::D()"<<endl;
}

void func()
{
cout<<"D::func()"<<endl;
boost::shared_ptr<D> p = shared_from_this();
}
};

int main()
{
boost::shared_ptr<D> p(new D);
p->func();
return 0;
}
网上解释:
这里 boost::shared_ptr<D> d(new D) 实际上执行了 3 个动作:首先调用 enable_shared_from_this<D> 的构造函数;其次调用 D 的构造函数;最后调用 shared_ptr<D> 的构造函数。是第 3 个动作设置了 enable_shared_from_this<D> 的 weak_ptr 。
这个地方是很违背 c++ 常理和逻辑的,必须小心。

我想知道第三个动作是怎么设置了 enable_shared_from_this<D> 的 weak_ptr?详细点,网上的资料看了很多,这里还是不懂。还有就是求推荐一本学习boost的书籍,谢谢
...全文
217 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
神奕 2014-08-28
  • 打赏
  • 举报
回复
《Boost程序库完全开发指南》 还有这里:http://zh.highscore.de/cpp/boost/
jwj070524 2014-08-28
  • 打赏
  • 举报
回复
给你找到源代码,如果你知道shared_ptr和weak_ptr各自的功能的话能理解的更快一点。

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

64,651

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧