当前位置: 首页 > 工具软件 > Enable Copy > 使用案例 >

C++ enable_shared_from_this 解析

邵和硕
2023-12-01

GCC源码

// enable_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);
  }

  weak_ptr<_Tp> weak_from_this() noexcept { return _M_weak_this; }

  weak_ptr<const _Tp> weak_from_this() const noexcept { return _M_weak_this; }

 private:
  // 注意:这个函数与 weak_ptr 与 shared_ptr 有着千丝万缕的联系
  // 作用应该是在某个合适的时机,将 _M_weak_this 绑定到 this 上
  template <typename _Tp1>
  void _M_weak_assign(_Tp1* __p, const __shared_count<>& __n) const noexcept {
    _M_weak_this._M_assign(__p, __n);
  }

  // Found by ADL when this is an associated class.
  friend const enable_shared_from_this* __expt_enable_shared_from_this_base(
      const enable_shared_from_this* __p) {
    return __p;
  }

  template <typename>
  friend class shared_ptr;

  mutable weak_ptr<_Tp> _M_weak_this;
};

用 weak_ptr 构造 shared_ptr :

// copy constructors (6) 
template <class U> explicit shared_ptr (const weak_ptr<U>& x);

C++ 文档解释该构造函数如下:

  • copy constructors (6)
    If x is not empty, the object shares ownership of x’s assets and increases the use count.
    If x is empty, an empty object is constructed (as if default-constructed).
  • copy from weak_ptr (7)
    Same as above (6), except that if x has expired, a bad_weak_ptr exception is thrown.
 类似资料: