enable_shared_from_this
用途:
enable_shared_from_this
是一个基类模板,用于解决在类成员函数中获取类对象的 shared_ptr
的需求。它提供了一种机制,使类能够安全地从成员函数内部获得指向自身的 shared_ptr
。
- 解决对象生命周期管理问题:在某些情况下,需要在类的成员函数中获取指向同一对象的
shared_ptr
,以确保对象在函数执行期间不被销毁。而直接使用shared_ptr
可能会导致循环引用,造成内存泄漏。enable_shared_from_this
提供了一种避免循环引用的方法,通过调用shared_from_this()
函数获取指向自身的shared_ptr
,而不会增加引用计数。 - 安全地传递对象引用:有时候需要将类对象作为参数传递给其他函数或线程,以确保对象的有效性和一致性。使用
shared_ptr
可以方便地传递对象的共享所有权,从而避免对象在使用过程中被意外销毁。
所以引用带着两层含义:
- 自己引用自己,且不能增加引用计数,用enable_shared_from_this
- other引用自己,且不能增加引用计数,用weak_ptr
下面是一个示例代码,展示了 enable_shared_from_this
的用法:
#include <iostream>
#include <memory>class MyClass : public std::enable_shared_from_this<MyClass>
{
public:std::shared_ptr<MyClass> getShared(){return shared_from_this();}
};int main()
{std::shared_ptr<MyClass> obj1 = std::make_shared<MyClass>();std::shared_ptr<MyClass> obj2 = obj1->getShared();std::cout << "obj1 use count: " << obj1.use_count() << std::endl; // 输出为2std::cout << "obj2 use count: " << obj2.use_count() << std::endl; // 输出为2return 0;
}
C:\Users\yuyi.di\CLionProjects\untitled\cmake-build-debug\untitled.exe
obj1 use count: 2
obj2 use count: 2
shared_from_this()不能在构造函数里调用,因为在构造对象的时候,它还没有被交给shared_ptr接管。
该类的定义:
template<typename _Tp>class enable_shared_from_this{protected:enable_shared_from_this() { }enable_shared_from_this(const enable_shared_from_this&) { }enable_shared_from_this&operator=(const enable_shared_from_this&){ return *this; }~enable_shared_from_this() { }public:shared_ptr<_Tp>shared_from_this(){ return shared_ptr<_Tp>(this->_M_weak_this); }shared_ptr<const _Tp>shared_from_this() const{ return shared_ptr<const _Tp>(this->_M_weak_this); }private:template<typename _Tp1>void_M_weak_assign(_Tp1* __p, const __shared_count<>& __n) const{ _M_weak_this._M_assign(__p, __n); }template<typename _Tp1>friend void__enable_shared_from_this_helper(const __shared_count<>& __pn,const enable_shared_from_this* __pe,const _Tp1* __px){if (__pe != 0)__pe->_M_weak_assign(const_cast<_Tp1*>(__px), __pn);}mutable weak_ptr<_Tp> _M_weak_this;};