C++ std::enable_shared_from_this知识点整理

1、std::enable_shared_from_this是什么?

std::enable_shared_from_this是一个模板类,具体调用时头文件如下:

#include <memory>

其定义如下:

 /**
   *  @brief Base class allowing use of member function shared_from_this.
   */
  template<typename _Tp>
    class enable_shared_from_this
    {
    protected:
      constexpr enable_shared_from_this() noexcept { }

      enable_shared_from_this(const enable_shared_from_this&) noexcept { }

      enable_shared_from_this&
      operator=(const enable_shared_from_this&) noexcept
      { 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 noexcept
	{ _M_weak_this._M_assign(__p, __n); }

      template<typename _Tp1, typename _Tp2>
	friend void
	__enable_shared_from_this_helper(const __shared_count<>&,
					 const enable_shared_from_this<_Tp1>*,
					 const _Tp2*) noexcept;

      mutable weak_ptr<_Tp>  _M_weak_this;
    };

  template<typename _Tp1, typename _Tp2>
    inline void
    __enable_shared_from_this_helper(const __shared_count<>& __pn,
				     const enable_shared_from_this<_Tp1>*
				     __pe, const _Tp2* __px) noexcept
    {
      if (__pe != nullptr)
	__pe->_M_weak_assign(const_cast<_Tp2*>(__px), __pn);
    }

  /**
   *  @brief  Create an object that is owned by a shared_ptr.
   *  @param  __a     An allocator.
   *  @param  __args  Arguments for the @a _Tp object's constructor.
   *  @return A shared_ptr that owns the newly created object.
   *  @throw  An exception thrown from @a _Alloc::allocate or from the
   *          constructor of @a _Tp.
   *
   *  A copy of @a __a will be used to allocate memory for the shared_ptr
   *  and the new object.
   */
  template<typename _Tp, typename _Alloc, typename... _Args>
    inline shared_ptr<_Tp>
    allocate_shared(const _Alloc& __a, _Args&&... __args)
    {
      return shared_ptr<_Tp>(_Sp_make_shared_tag(), __a,
			     std::forward<_Args>(__args)...);
    }

  /**
   *  @brief  Create an object that is owned by a shared_ptr.
   *  @param  __args  Arguments for the @a _Tp object's constructor.
   *  @return A shared_ptr that owns the newly created object.
   *  @throw  std::bad_alloc, or an exception thrown from the
   *          constructor of @a _Tp.
   */
  template<typename _Tp, typename... _Args>
    inline shared_ptr<_Tp>
    make_shared(_Args&&... __args)
    {
      typedef typename std::remove_const<_Tp>::type _Tp_nc;
      return std::allocate_shared<_Tp>(std::allocator<_Tp_nc>(),
				       std::forward<_Args>(__args)...);
    }

  /// std::hash specialization for shared_ptr.
  template<typename _Tp>
    struct hash<shared_ptr<_Tp>>
    : public __hash_base<size_t, shared_ptr<_Tp>>
    {
      size_t
      operator()(const shared_ptr<_Tp>& __s) const noexcept
      { return std::hash<_Tp*>()(__s.get()); }
    };

如果一个_Tp类型的对象t,是通过进行std::shared_ptr管理的。当它且类型_Tp继承自std::enable_shared_from_this,那么_Tp就有个shared_from_this的成员函数。这个函数的作用返回一个新的std::shared_ptr的对象,也指向该对象,这就会使得std::shared_ptr的引用计数+1。这个作用就是保证不管同步还是异步操作时,其操作的对象都是有效的。

2、std::enable_shared_from_this的使用示例

具体的使用示例如下:

/*************************************************************************
      > File Name: enable_shared_from_this.cpp
      > Author: 小和尚念经敲木鱼
      > Mail:  
      > Created Time: Mon 30 Aug 2021 07:37:10 PM CST
 ***********************************************************************/
#include <iostream>
#include <memory>
using namespace std;
/************************************************************************
* 文件说明
************************************************************************/
//Base继承enable_shared_from_this模板类并实例Base
class Base : public std::enable_shared_from_this<Base>
{
public:
  Base()
  {
    std::cout << "Base:" << __func__ <<std::endl;
  }
  std::shared_ptr<Base> getptr() {
    return shared_from_this();
  }
  ~Base()
  {
    std::cout << "Base::" << __func__ << std::endl;
  }
};
int main(int agc,char * agv[])
{
	std::shared_ptr<Base> p1 (new Base());
	std::shared_ptr<Base> p2 = p1->getptr();
	std::cout << "p1 use count = " << p1.use_count() << std::endl;
	std::cout << "p2 use count = " << p2.use_count() << std::endl;
	p1.reset();
	p2.reset();
	return 0;
}
//OUT
//Base:Base
//p1 use count = 2
//p2 use count = 2
//Base::~Base
/******************************end of file******************************/

3、总结和拓展

待续…

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

给大佬递杯卡布奇诺

你们的鼓励就是我传作的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值