enable_shared_from_this 的使用及原理

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(_internal_weak_this);
        BOOST_ASSERT(p.get() == this);
        return p;
    }

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

// Note: No, you don't need to initialize _internal_weak_this

//

// Please read the documentation, not the code

//

// http://www.boost.org/libs/smart_ptr/enable_shared_from_this.html


    typedef T _internal_element_type; // for bcc 5.5.1

    mutable weak_ptr<_internal_element_type> _internal_weak_this;
};

``

class Y: public enable_shared_from_this
{
public:

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

}

int main()
{
shared_ptr p(new Y);
// 调用f获得shared_ptr

shared_ptr<Y> q = p->f();
assert(p == q);
assert(!(p < q || q < p)); // p and q must share ownership

}
“`

参考资料:http://www.boost.org/doc/libs/1_62_0/libs/smart_ptr/enable_shared_from_this.html

http://en.cppreference.com/w/cpp/memory/enable_shared_from_this

enable_shared_from_this 的原理:
http://blog.csdn.net/zhongguoren666/article/details/8617436

http://blog.csdn.net/zhongguoren666/article/details/8618316

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值