std::shared_from_this注意事项:exception bad_weak_ptr

1.不可以在构造函数中调用shared_from_this()
因为它的实现是:

    _LIBCPP_INLINE_VISIBILITY
    shared_ptr<_Tp> shared_from_this()
        {return shared_ptr<_Tp>(__weak_this_);}

也就是它依赖的__weak_this_此时还未创建完成。

2.一定要public继承

class MyType : public std::enable_shared_from_this<MyType> {
}

以macOS平台的实现为例:
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX14.0.sdk/usr/include/c++/v1/__memory/shared_ptr.h

shared_ptr的构造过程,需要调用__enable_weak_this()初始化__weak_this_
__enable_weak_this的实现,会根据类型的可见性,利用模板特化了不同的实现。

正确的实现:

    template <class _Yp, class _OrigPtr, class = __enable_if_t<
        is_convertible<_OrigPtr*, const enable_shared_from_this<_Yp>*>::value
    > >
    _LIBCPP_HIDE_FROM_ABI
    void __enable_weak_this(const enable_shared_from_this<_Yp>* __e, _OrigPtr* __ptr) _NOEXCEPT
    {
        typedef __remove_cv_t<_Yp> _RawYp;
        if (__e && __e->__weak_this_.expired())
        {
            __e->__weak_this_ = shared_ptr<_RawYp>(*this,
                const_cast<_RawYp*>(static_cast<const _Yp*>(__ptr)));
        }
    }

空实现:

    _LIBCPP_HIDE_FROM_ABI void __enable_weak_this(...) _NOEXCEPT { }

可见性不符合时,无法正确创建出__weak_this_。此时使用std::enable_shared_from_this<T>便失去了意义。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值