1.不可以在構造函數中調用shared_from_this()
因為它的實現是:
_LIBCPP_INLINE_VISIBILITYshared_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_ABIvoid __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>
便失去了意義。