enable_shared_from_this
是一个类,继承后的作用是使用shared_ptr<T>
管理的对象的this
指针以shared_ptr
传递到其他函数,当然并不是直接传this
,而是通过继承后的一个public
方法shared_from_this
来生成shared_ptr
指向自己的指针。
大概使用方式(即在下面代码中调用shared_from_this
获取指向自身的shared_ptr
):
class B;
class A:public enable_shared_from_this{
public:
shared_ptr<B> get(Key key){
auto p=_map[key].lock();
if(!p){
p.reset(new B(key),bind(&A::deleteB,shared_from_this(),_1); //获取指向this的shared_ptr
weak_ptr<B>r=p;
_map[key]=r;
}
return p;
}
private:
void deleteB(B *b){
...
...
}
map<Key,weak_ptr<B>>_map;
};
int main(){
shared_ptr<A> p(new A); //注意这里
...
...
}
以下是便是enable_shared_from_this
类的源码:(VS2017)
template<class _Ty>
class enable_shared_from_this
{ // provide member functions that create shared_ptr to this
public:
using _Esft_type = enable_shared_from_this;
_NODISCARD shared_ptr<_Ty> shared_from_this()
{ // return shared_ptr
return (shared_ptr<_Ty>(_Wptr));
}
_NODISCARD shared_ptr<const _Ty> shared_from_this() const
{ // return shared_ptr
return (shared_ptr<const _Ty>(_Wptr));
}
_NODISCARD weak_ptr<_Ty> weak_from_this() noexcept
{ // return weak_ptr
return (_Wptr);
}
_NODISCARD weak_ptr<const _Ty> weak_from_this() const noexcept
{ // return weak_ptr
return (_Wptr);
}
protected:
constexpr enable_shared_from_this() noexcept
: _Wptr()
{ // construct
}
enable_shared_from_this(const enable_shared_from_this&) noexcept
: _Wptr()
{ // construct (must value-initialize _Wptr)
}
enable_shared_from_this& operator=(const enable_shared_from_this&) noexcept
{ // assign (must not change _Wptr)
return (*this);
}
~enable_shared_from_this() = default;
private:
template<class _Other,
class _Yty>
friend void _Enable_shared_from_this1(const shared_ptr<_Other>& _This, _Yty * _Ptr, true_type);
mutable weak_ptr<_Ty> _Wptr;
};
从源码中,我们可以看到类成员变量中有一个weak_ptr
,这也就是实现一个指向自己的shared_ptr
的关键,而我们可以看到,似乎类中没有成员方法能够初始化weak_ptr
的,所以就只有_Enable_shared_from_this1
是我们要关注的点。
其代码:
template<class _Other,
class _Yty>
void _Enable_shared_from_this1(const shared_ptr<_Other>& _This, _Yty * _Ptr, true_type)
{ // enable shared_from_this
if (_Ptr && _Ptr->_Wptr.expired())
{
_Ptr->_Wptr = shared_ptr<remove_cv_t<_Yty>>(_This, const_cast<remove_cv_t<_Yty> *>(_Ptr));
}
}
该函数出现在enable_shared_from_this
中,参数中_This
是一个shared_ptr
,而_Ptr
包含_Wptr
,基本上可以推断出,_Yty
类型应该是enable_shared_from_this
类,而该类的_Wptr
在这里被赋值,指向一个_Yty
的智能指针。
那么,这个函数是在哪里调用呢?结合使用方式来看,调用的地方就只有在shared_ptr
构建的时候调用,即上面使用方式中,在main
函数中使用shared_ptr<A>
构建中调用,其中A
继承enable_shared_from_this
。
即在构建的时候构建一个weak_ptr
自身智能指针的观察者,当使用的时候将weak
提升至shared
,从而达到shared_ptr
自身的效果。