GCC12.2 C++11 智能指针代码走读

以引用计数为基础的智能指针,引用计数的管理逻辑如下:

  • 除了初始化对象本身外,每个构造函数(拷贝构造函数除外)还要在堆上创建一个引用计数,用来记录有多少个对象共享状态。当我们创建一个对象时,只有一个对象共享状态,因此将引用计数初始化为 1;
  • 拷贝构造函数不分配新的计数器,而是拷贝给定对象的数据成员,包括计数器。拷贝构造函数递增共享的计数器,标记给定对象的状态又被一个新用户所共享
  • 析构函数递减计数器,标记共享状态的用户少了一个。如果计数器变为 0,则析构函数析构对象,包括引进计数变量;
  • 拷贝赋值运算符递增右侧运算对象的计数器,递减左侧运算对象的计数器。如果左侧运算对象的计数器变为 0,意味着它的共享状态没有用户了,拷贝运算符就必须销毁状态;
  • 计数器一般保存在动态内存中。当创建一个对象时,也分配一个新的计数器。当拷贝或赋值对象时,拷贝指向计数器的指针。使用这种方法,副本和原对象都会指向相同的计数器

1、std::shared_ptr

首先我们看看 shared_ptr 相关的类,主要是 __shared_ptr、__shared_count 和 、_Sp_counted_base 这三个。shared_ptr 继承 __shared_ptr,__shared_ptr 有两个成员变量:对象指针和引用计数。引用计数 __shared_count 主要借助 _Sp_counted_base 实现。

/// shared_ptr.h
  template<typename _Tp>
    class shared_ptr : public __shared_ptr<_Tp>
    {
        /* ... */
      friend class weak_ptr<_Tp>;
    };

/// shared_ptr_base.h
  template<typename _Tp, _Lock_policy _Lp>
    class __shared_ptr
    : public __shared_ptr_access<_Tp, _Lp>
    {
    public:
     using element_type = typename remove_extent<_Tp>::type;

        /* ... */
      element_type*       _M_ptr;         // Contained pointer.
      __shared_count<_Lp>  _M_refcount;    // Reference counter.
    };

/// shared_ptr_base.h
  template<_Lock_policy _Lp>
    class __shared_count
    {
        /* ... */
      _Sp_counted_base<_Lp>*  _M_pi;
    };

/// shared_ptr_base.h
  template<_Lock_policy _Lp = __default_lock_policy>
    class _Sp_counted_base
    : public _Mutex_base<_Lp>
    {
        /* .... */
    }

shared_ptr 是一个模板类,继承 __shared_ptr 模板类,具体的实现都在基类,常用的接口如下

reset

replaces the managed object (public member function)

swap

swaps the managed objects (public member function)

get

returns the stored pointer (public member function)

operator*operator->

dereferences the stored pointer (public member function)

[operator

]

(C++17)

provides indexed access to the stored array (public member function)

use_count

returns the number of

 

shared_ptr

 

objects referring to the same managed object (public member function)

unique

(until C++20)

checks whether the managed object is managed only by the current

 

shared_ptr

 

instance (public member function)

operator bool

checks if the stored pointer is not null (public member function)

owner_before

provides owner-based ordering of shared pointers (public member function)

1.1、_Sp_counted_base

_Sp_counted_base 继承于 _Mutex_base,首先分析 _Mutex_base。

1.1.1、_Mutex_base

_Mutex_base 是为了处理多线程加锁问题,_Lock_policy 有三个取值

  • _S_single:单线程,不考虑锁
  • _S_mutex:使用互斥锁
  • _S_atomic:使用原子操作

默认情况下,__default_lock_policy 的值是 _S_atomic(本文也只讨论 _Lock_policy 为 _S_atomic 的情况)

/// concurrence.h
  // Available locking policies:
  // _S_single    single-threaded code that doesn't need to be locked.
  // _S_mutex     multi-threaded code that requires additional support
  //              from gthr.h or abstraction layers in concurrence.h.
  // _S_atomic    multi-threaded code using atomic operations.
  enum _Lock_policy { _S_single, _S_mutex, _S_atomic }; 

  // Compile time constant that indicates prefered locking policy in
  // the current configuration.
  static const _Lock_policy __default_lock_policy = 
#ifndef __GTHREADS
  _S_single;
#elif defined _GLIBCXX_HAVE_ATOMIC_LOCK_POLICY
  _S_atomic;
#else
  _S_mutex;
#endif

弄清楚 _Lock_policy 和 __default_lock_policy 后,_Mutex_base 只有在模板参数 _Lp 为 _S_mutex,_S_need_barriers 才会被赋值为 1。

/// shared_ptr_base.h
  // Empty helper class except when the template argument is _S_mutex.
  template<_Lock_policy _Lp>
    class _Mutex_base
    {
    protected:
      // The atomic policy uses fully-fenced builtins, single doesn't care.
      enum { _S_need_barriers = 0 };
    };

  template<>
    class _Mutex_base<_S_mutex>
    : public __gnu_cxx::__mutex
    {
    protected:
      // This policy is used when atomic builtins are not available.
      // The replacement atomic operations might not have the necessary
      // memory barriers.
      enum { _S_need_barriers = 1 };
    };

1.1.2、_Sp_counted_base

_Sp_counted_base 在定义时,模板参数 _Lp 被赋值为 __default_lock_policy,则 _S_need_barriers 为 0。

另外,_Sp_counted_base 有两个表示引用计数的成员变量:_M_use_count 和 _M_weak_count,分别表示当前有多少个 shared_ptr 和 weak_ptr 指向某对象。另外,如果 _M_use_count 不为 0,_M_weak_count 至少为 1。

_Sp_counted_base 不仅充当引用计数功能,还负责管理资源,即

  • 当 _M_use_count 递减为 0 时,调用 _M_dispose() 释放 *this 管理的资源
  • 当 _M_weak_count 递减为 0 时,调用 _M_destroy() 释放 *this 对象

_M_dispose() 是纯虚函数,由派生类实现。

/// shared_ptr_base.h
  template<_Lock_policy _Lp = __default_lock_policy>
    class _Sp_counted_base
    : public _Mutex_base<_Lp>
    {
    public:
      _Sp_counted_base() noexcept
      : _M_use_count(1), _M_weak_count(1) { }

      virtual
      ~_Sp_counted_base() noexcept
      { }

      // Called when _M_use_count drops to zero, to release the resources
      // managed by *this.
      virtual void
      _M_dispose() noexcept = 0;

      // Called when _M_weak_count drops to zero.
      virtual void
      _M_destroy() noexcept
      { delete this; } /*** 释放引用计数变量内存 ***/

      virtual void*
      _M_get_deleter(const std::type_info&) noexcept = 0;

        /* ... */

    private:
      _Sp_counted_base(_Sp_counted_base const&) = delete;
      _Sp_counted_base& operator=(_Sp_counted_base const&) = delete;

      _Atomic_word  _M_use_count;     // #shared
      _Atomic_word  _M_weak_count;    // #weak + (#shared != 0)
    };

1)++_M_use_count

递增 _M_use_count 的接口有三个

  • _M_add_ref_copy():在 use count 大于 0 时使用(调用者自己确保)
  • _M_add_ref_lock():当 use count 为 0,抛出异常
  • _M_add_ref_lock():当 use count 为 0,返回 false,否则递增,返回 true
/// shared_ptr_base.h
      // Increment the use count (used when the count is greater than zero).
      void
      _M_add_ref_copy()
      { __gnu_cxx::__atomic_add_dispatch(&_M_use_count, 1); }

      // Increment the use count if it is non-zero, throw otherwise.
      void
      _M_add_ref_lock()
      {
    if (!_M_add_ref_lock_nothrow())
      __throw_bad_weak_ptr();
      }

      // Increment the use count if it is non-zero.
  template<>
    inline bool
    _Sp_counted_base<_S_atomic>::
    _M_add_ref_lock_nothrow() noexcept
    {
      // Perform lock-free add-if-not-zero operation.
      _Atomic_word __count = _M_get_use_count();
      do
    {
      if (__count == 0)
        return false;
      // Replace the current counter value with the old value + 1, as
      // long as it's not changed meanwhile.
    }
      while (!__atomic_compare_exchange_n(&_M_use_count, &__count, __count + 1,
                      true, __ATOMIC_ACQ_REL,
                      __ATOMIC_RELAXED));
      return true;
    }

2)++_M_weak_count

递增 _M_weak_count 的接口 _M_weak_add_ref。

/// shared_ptr_base.h
      // Increment the weak count.
      void
      _M_weak_add_ref() noexcept
      { __gnu_cxx::__atomic_add_dispatch(&_M_weak_count, 1); }

3)_M_release()

_M_release() 递减 _M_use_count,当 use count 为 0,调用 _M_release_last_use() 函数。

/// shared_ptr_base.h

  template<>
    inline void
    _Sp_counted_base<_S_atomic>::_M_release() noexcept
    {
      _GLIBCXX_SYNCHRONIZATION_HAPPENS_BEFORE(&_M_use_count);
#if ! _GLIBCXX_TSAN
/* ... */
#endif
      if (__gnu_cxx::__exchange_and_add_dispatch(&_M_use_count, -1) == 1)
    {
      _M_release_last_use();
    }
    }

_M_release_last_use() 函数先调用 _M_dispose() 函数,然后递减 weak count。weak count 递减为 0,调用 _M_destroy() 函数释放 *this 对象。

为什么 user count 递减为 0,需要递减 weak count?原因在于 weak count 的计数方式 #weak + (#shared != 0),如果 user count 递减为 0,shared 就为 0,那么 weak count 应当减 1。

/// shared_ptr_base.h

      // Called by _M_release() when the use count reaches zero.
      void
      _M_release_last_use() noexcept
      {
    _GLIBCXX_SYNCHRONIZATION_HAPPENS_AFTER(&_M_use_count);
    _M_dispose();
/* ... */
    if (__gnu_cxx::__exchange_and_add_dispatch(&_M_weak_count,
                           -1) == 1)
      {
        _GLIBCXX_SYNCHRONIZATION_HAPPENS_AFTER(&_M_weak_count);
        _M_destroy();
      }
      }

4)_M_weak_release()

_M_weak_release() 递减 weak count,如果 weak count 为 0,调用 _M_destroy() 释放 *this 对象。

/// shared_ptr_base.h

      // Decrement the weak count.
      void
      _M_weak_release() noexcept
      {
        // Be race-detector-friendly. For more info see bits/c++config.
        _GLIBCXX_SYNCHRONIZATION_HAPPENS_BEFORE(&_M_weak_count);
    if (__gnu_cxx::__exchange_and_add_dispatch(&_M_weak_count, -1) == 1)
      {
            _GLIBCXX_SYNCHRONIZATION_HAPPENS_AFTER(&_M_weak_count);
        if (_Mutex_base<_Lp>::_S_need_barriers)
          {
            // See _M_release(),
            // destroy() must observe results of dispose()
        __atomic_thread_fence (__ATOMIC_ACQ_REL);
          }
        _M_destroy();
      }
      }

1.1.3、_Sp_counted_ptr

/// shared_ptr_base.h

  // Counted ptr with no deleter or allocator support
  template<typename _Ptr, _Lock_policy _Lp>
    class _Sp_counted_ptr final : public _Sp_counted_base<_Lp>
    {
    public:
      explicit
      _Sp_counted_ptr(_Ptr __p) noexcept
      : _M_ptr(__p) { }

      virtual void
      _M_dispose() noexcept
      { delete _M_ptr; }

      virtual void
      _M_destroy() noexcept
      { delete this; }

      virtual void*
      _M_get_deleter(const std::type_info&) noexcept
      { return nullptr; }

      _Sp_counted_ptr(const _Sp_counted_ptr&) = delete;
      _Sp_counted_ptr& operator=(const _Sp_counted_ptr&) = delete;

    private:
      _Ptr             _M_ptr;
    };

  template<>
    inline void
    _Sp_counted_ptr<nullptr_t, _S_atomic>::_M_dispose() noexcept { }

1.1.4、_Sp_counted_deleter

_Sp_counted_deleter::_Impl 继承 _Sp_ebo_helper 处理 Deleter 和 Alloc,然后定义一个成员变量 _M_ptr 保存传入指针。

构造和析构函数不同在意,特别分析 _M_dispose 和 _M_destroy 的实现。

/// shared_ptr_base.h
  // Support for custom deleter and/or allocator
  template<typename _Ptr, typename _Deleter, typename _Alloc, _Lock_policy _Lp>
    class _Sp_counted_deleter final : public _Sp_counted_base<_Lp>
    {
      class _Impl : _Sp_ebo_helper<0, _Deleter>, _Sp_ebo_helper<1, _Alloc>
      {
    typedef _Sp_ebo_helper<0, _Deleter>    _Del_base;
    typedef _Sp_ebo_helper<1, _Alloc>    _Alloc_base;

      public:
    _Impl(_Ptr __p, _Deleter __d, const _Alloc& __a) noexcept
    : _Del_base(std::move(__d)), _Alloc_base(__a), _M_ptr(__p)
    { }

    _Deleter& _M_del() noexcept { return _Del_base::_S_get(*this); }
    _Alloc& _M_alloc() noexcept { return _Alloc_base::_S_get(*this); }

    _Ptr _M_ptr;
      };

    public:
      using __allocator_type = __alloc_rebind<_Alloc, _Sp_counted_deleter>;

      // __d(__p) must not throw.
      _Sp_counted_deleter(_Ptr __p, _Deleter __d) noexcept
      : _M_impl(__p, std::move(__d), _Alloc()) { }

      // __d(__p) must not throw.
      _Sp_counted_deleter(_Ptr __p, _Deleter __d, const _Alloc& __a) noexcept
      : _M_impl(__p, std::move(__d), __a) { }

      ~_Sp_counted_deleter() noexcept { }

        /* ... */

    private:
      _Impl _M_impl;
    };

_M_dispose() 函数调用 user 传入的 Delter 处理 _M_ptr 指向的对象。_M_get_deleter() 也是返回 user 传入的 Deleter。

/// shared_ptr_base.h
      virtual void
      _M_dispose() noexcept
      { _M_impl._M_del()(_M_impl._M_ptr); }

      virtual void*
      _M_get_deleter(const type_info& __ti [[__gnu__::__unused__]]) noexcept
      {
#if __cpp_rtti
    // _GLIBCXX_RESOLVE_LIB_DEFECTS
    // 2400. shared_ptr's get_deleter() should use addressof()
        return __ti == typeid(_Deleter)
      ? std::__addressof(_M_impl._M_del())
      : nullptr;
#else
        return nullptr;
#endif
      }

_M_destroy() 没有特殊的处理,调用析构函数。

/// shared_ptr_base.h
      virtual void
      _M_destroy() noexcept
      {
    __allocator_type __a(_M_impl._M_alloc());
    __allocated_ptr<__allocator_type> __guard_ptr{ __a, this };
    this->~_Sp_counted_deleter();
      }

1.1.5、_Sp_counted_ptr_inplace

_Sp_counted_ptr_inplace 和 _Sp_counted_deleter 的实现类似,唯一的差别是 _Sp_counted_ptr_inplace::_Impl 成员变量不是 user 传入的指针,而是一块足以放下 _Tp 的一块内存。

/// shared_ptr_base.h
  template<typename _Tp, typename _Alloc, _Lock_policy _Lp>
    class _Sp_counted_ptr_inplace final : public _Sp_counted_base<_Lp>
    {
      class _Impl : _Sp_ebo_helper<0, _Alloc>
      {
    typedef _Sp_ebo_helper<0, _Alloc>    _A_base;

      public:
    explicit _Impl(_Alloc __a) noexcept : _A_base(__a) { }

    _Alloc& _M_alloc() noexcept { return _A_base::_S_get(*this); }

    __gnu_cxx::__aligned_buffer<_Tp> _M_storage;
      };

    public:
      using __allocator_type = __alloc_rebind<_Alloc, _Sp_counted_ptr_inplace>;

      // Alloc parameter is not a reference so doesn't alias anything in __args
      template<typename... _Args>
    _Sp_counted_ptr_inplace(_Alloc __a, _Args&&... __args)
    : _M_impl(__a)
    {
      // _GLIBCXX_RESOLVE_LIB_DEFECTS
      // 2070.  allocate_shared should use allocator_traits<A>::construct
      allocator_traits<_Alloc>::construct(__a, _M_ptr(),
          std::forward<_Args>(__args)...); // might throw
    }

      ~_Sp_counted_ptr_inplace() noexcept { }

      virtual void
      _M_dispose() noexcept
      {
    allocator_traits<_Alloc>::destroy(_M_impl._M_alloc(), _M_ptr());
      }

      // Override because the allocator needs to know the dynamic type
      virtual void
      _M_destroy() noexcept
      {
    __allocator_type __a(_M_impl._M_alloc());
    __allocated_ptr<__allocator_type> __guard_ptr{ __a, this };
    this->~_Sp_counted_ptr_inplace(); /* 析构 _M_impl 对象 */
      }

    private:
      friend class __shared_count<_Lp>; // To be able to call _M_ptr().

      // No longer used, but code compiled against old libstdc++ headers
      // might still call it from __shared_ptr ctor to get the pointer out.
      virtual void*
      _M_get_deleter(const std::type_info& __ti) noexcept override
      {
    auto __ptr = const_cast<typename remove_cv<_Tp>::type*>(_M_ptr());
    // Check for the fake type_info first, so we don't try to access it
    // as a real type_info object. Otherwise, check if it's the real
    // type_info for this class. With RTTI enabled we can check directly,
    // or call a library function to do it.
    if (&__ti == &_Sp_make_shared_tag::_S_ti()
        ||
#if __cpp_rtti
        __ti == typeid(_Sp_make_shared_tag)
#else
        _Sp_make_shared_tag::_S_eq(__ti)
#endif
       )
      return __ptr;
    return nullptr;
      }

      _Tp* _M_ptr() noexcept { return _M_impl._M_storage._M_ptr(); }

      _Impl _M_impl;
    };

1.1.6、总结

_Sp_counted_base 不仅充当引用计数功能,还充当内存管理功能。从上面的分析可以看到,_Sp_counted_base 负责释放 user 申请的内存,即

  • 当 _M_use_count 递减为 0 时,调用 _M_dispose() 释放 this 管理的资源
  • 当 _M_weak_count 递减为 0 时,调用 _M_destroy() 释放 this 对象

1.2、__shared_count

__shared_count 只有一个指针类型成员变量 _M_pi,是基类 _Sp_counted_base<_Lp> 类型的指针。

__shared_count 有意思的是构造函数的实现,通过分析我们将会看到传入不同的参数类型,_M_pi 将会指向具体对象:

  • _Sp_counted_ptr,只有管理对象的指针,默认用 delete 释放管理的函数;
  • _Sp_counted_deleter,除了管理对象的指针,还有善后函数 deleter(),在析构时调用 deleter(),不再调用 delete 释放对象,相当于用用户指定的方式释放对象;
  • _Sp_counted_ptr_inplace,std::make_shared() 申请的对象,管理的对象和引用计数在同一块内存上;

1.2.1、传入裸指针

传入裸指针是指我们自己 new 一个对象,然后用该对象构造 shared_ptr,比如类似如下方式

class Foo {
 public:
  Foo(int val): val(val), next(nullptr) {}
  int val;
  Foo* next;
};

std::shared_ptr<Foo> ptr(new Foo(-1));

此时,_M_pi 指向 _Sp_counted_ptr 类型的对象,调用构造函数如下

/// shared_ptr_base.h
      template<typename _Ptr>
        explicit
    __shared_count(_Ptr __p) : _M_pi(0)
    {
      __try
        {
          _M_pi = new _Sp_counted_ptr<_Ptr, _Lp>(__p);
        }
      __catch(...)
        {
          delete __p;
          __throw_exception_again;
        }
    }

1.2.2、指定 Deleter

在构造 shared_ptr 时如果指定了 Deleter,类似于如下方法

struct Deleter {
  void operator()(Foo* p) const {
    std::cout << "Call delete from function object...\n";
    delete p;
  }
};

std::shared_ptr<Foo> ptr(new Foo(-1), Deleter());

此时,_M_pi 指向 _Sp_counted_deleter 类型的对象,调用构造函数如下

/// shared_ptr_base.h
      template<typename _Ptr, typename _Deleter, typename _Alloc,
           typename = typename __not_alloc_shared_tag<_Deleter>::type>
    __shared_count(_Ptr __p, _Deleter __d, _Alloc __a) : _M_pi(0)
    {
      typedef _Sp_counted_deleter<_Ptr, _Deleter, _Alloc, _Lp> _Sp_cd_type;
      __try
        {
          typename _Sp_cd_type::__allocator_type __a2(__a);
          auto __guard = std::__allocate_guarded(__a2);
          _Sp_cd_type* __mem = __guard.get();
          ::new (__mem) _Sp_cd_type(__p, std::move(__d), std::move(__a));
          _M_pi = __mem;
          __guard = nullptr;
        }
      __catch(...)
        {
          __d(__p); // Call _Deleter on __p.
          __throw_exception_again;
        }
    }

1.2.3、make_shared

使用 make_shared 的方法构造 shared_ptr 对象时,类似如下

std::shared_ptr<Foo> ptr = std::make_shared<Foo>(-1);

此时,_M_pi 指向 _Sp_counted_ptr_inplace 类型的对象,调用构造函数如下

/// shared_ptr_base.h
      template<typename _Tp, typename _Alloc, typename... _Args>
    __shared_count(_Tp*& __p, _Sp_alloc_shared_tag<_Alloc> __a,
               _Args&&... __args)
    {
      typedef _Sp_counted_ptr_inplace<_Tp, _Alloc, _Lp> _Sp_cp_type;
      typename _Sp_cp_type::__allocator_type __a2(__a._M_a);
      auto __guard = std::__allocate_guarded(__a2);
      _Sp_cp_type* __mem = __guard.get();
      auto __pi = ::new (__mem)
        _Sp_cp_type(__a._M_a, std::forward<_Args>(__args)...);
      __guard = nullptr;
      _M_pi = __pi;
      __p = __pi->_M_ptr();
    }

1.2.4、std::unique_ptr

当从 unique_ptr 构造 shared_ptr,类似于如下方法

std::unique_ptr<Foo> ptr(new Foo(-1));
std::shared_ptr<Foo> ptr2(ptr);

此时,_M_pi 指向 _Sp_counted_ptr 类型的对象,调用构造函数如下

/// shared_ptr_base.h
      // Special case for unique_ptr<_Tp,_Del> to provide the strong guarantee.
      template<typename _Tp, typename _Del>
        explicit
    __shared_count(std::unique_ptr<_Tp, _Del>&& __r) : _M_pi(0)
    {
      // _GLIBCXX_RESOLVE_LIB_DEFECTS
      // 2415. Inconsistency between unique_ptr and shared_ptr
      if (__r.get() == nullptr)
        return;

      using _Ptr = typename unique_ptr<_Tp, _Del>::pointer;
      using _Del2 = __conditional_t<is_reference<_Del>::value,
          reference_wrapper<typename remove_reference<_Del>::type>,
          _Del>;
      using _Sp_cd_type
        = _Sp_counted_deleter<_Ptr, _Del2, allocator<void>, _Lp>;
      using _Alloc = allocator<_Sp_cd_type>;
      using _Alloc_traits = allocator_traits<_Alloc>;
      _Alloc __a;
      _Sp_cd_type* __mem = _Alloc_traits::allocate(__a, 1);
      // _GLIBCXX_RESOLVE_LIB_DEFECTS
      // 3548. shared_ptr construction from unique_ptr should move
      // (not copy) the deleter
      _Alloc_traits::construct(__a, __mem, __r.release(),
                   std::forward<_Del>(__r.get_deleter()));
      _M_pi = __mem;
    }

1.2.5、拷贝赋值构造函数

从 __shared_count 的赋值构造函数,可以清楚的看到引起计数的管理:增右侧运算对象的计数器,递减左侧运算对象的计数器。

/// shared_ptr_base.h
      __shared_count&
      operator=(const __shared_count& __r) noexcept
      {
    _Sp_counted_base<_Lp>* __tmp = __r._M_pi;
    if (__tmp != _M_pi)
      {
        if (__tmp != nullptr)
          __tmp->_M_add_ref_copy();
        if (_M_pi != nullptr)
          _M_pi->_M_release();
        _M_pi = __tmp;
      }
    return *this;
      }

1.3、__shared_ptr

__shared_ptr 有两个数据域,一个存放对象指针,一个存放引用计数相关的结构。

另外,__shared_ptr 继承于 __shared_ptr_access,__shared_ptr_access 是为了重载运算符 operator*、operator-> 和 operator[] 的,这里不做介绍。

/// shared_ptr_base.h
  template<typename _Tp, _Lock_policy _Lp>
    class __shared_ptr
    : public __shared_ptr_access<_Tp, _Lp>
    {
    public:
     using element_type = typename remove_extent<_Tp>::type;
        /* ... */

      friend class __weak_ptr<_Tp, _Lp>;

        /* ... */
      element_type*       _M_ptr;         // Contained pointer.
      __shared_count<_Lp>  _M_refcount;    // Reference counter.
    };

__shared_ptr 我们重点分析构造函数,在某些构造函数中,_M_enable_shared_from_this_with() 函数。主要是如下几种情况

/// shared_ptr_base.h
      template<typename _Yp, typename = _SafeConv<_Yp>>
    explicit
    __shared_ptr(_Yp* __p)
    : _M_ptr(__p), _M_refcount(__p, typename is_array<_Tp>::type())
    {
      static_assert( !is_void<_Yp>::value, "incomplete type" );
      static_assert( sizeof(_Yp) > 0, "incomplete type" );
      _M_enable_shared_from_this_with(__p);
    }

      template<typename _Yp, typename _Deleter, typename = _SafeConv<_Yp>>
    __shared_ptr(_Yp* __p, _Deleter __d)
    : _M_ptr(__p), _M_refcount(__p, std::move(__d))
    {
      static_assert(__is_invocable<_Deleter&, _Yp*&>::value,
          "deleter expression d(p) is well-formed");
      _M_enable_shared_from_this_with(__p);
    }

      template<typename _Yp, typename _Deleter, typename _Alloc,
           typename = _SafeConv<_Yp>>
    __shared_ptr(_Yp* __p, _Deleter __d, _Alloc __a)
    : _M_ptr(__p), _M_refcount(__p, std::move(__d), std::move(__a))
    {
      static_assert(__is_invocable<_Deleter&, _Yp*&>::value,
          "deleter expression d(p) is well-formed");
      _M_enable_shared_from_this_with(__p);
    }

      template<typename _Yp, typename _Del,
           typename = _UniqCompatible<_Yp, _Del>>
    __shared_ptr(unique_ptr<_Yp, _Del>&& __r)
    : _M_ptr(__r.get()), _M_refcount()
    {
      auto __raw = __to_address(__r.get());
      _M_refcount = __shared_count<_Lp>(std::move(__r));
      _M_enable_shared_from_this_with(__raw);
    }

_M_enable_shared_from_this_with() 是 __weak_ptr 的成员函数,函数是为了实现 shared_from_this,稍后会有介绍。

虽然 __shared_count 也保存了对象指针,但是 __shared_ptr 并没有从 __shared_count 获取对象指针,而是使用自己保存的对象指针。

/// shared_ptr_base.h
      /// Return the stored pointer.
      element_type*
      get() const noexcept
      { return _M_ptr; }

      /// Return true if the stored pointer is not null.
      explicit operator bool() const noexcept
      { return _M_ptr != nullptr; }

另外,参数 __weak_ptr 的构造函数也需要先提示,当我看将 weak_ptr 提升为 shared_ptr 的时候,需要进入这个构造函数。

/// shared_ptr_base.h
      // This constructor is used by __weak_ptr::lock() and
      // shared_ptr::shared_ptr(const weak_ptr&, std::nothrow_t).
      __shared_ptr(const __weak_ptr<_Tp, _Lp>& __r, std::nothrow_t) noexcept
      : _M_refcount(__r._M_refcount, std::nothrow)
      {
    _M_ptr = _M_refcount._M_get_use_count() ? __r._M_ptr : nullptr;
      }

2、std::weak_ptr

不控制所指向对象生命周期的智能指针,它指向一个 shared_ptr 管理的对象

/// shared_ptr.h
  template<typename _Tp>
    class weak_ptr : public __weak_ptr<_Tp>
    {
        /* ... */
      shared_ptr<_Tp>
      lock() const noexcept
      { return shared_ptr<_Tp>(*this, std::nothrow); }
    };

/// shared_ptr_base.h
  template<typename _Tp, _Lock_policy _Lp>
    class __weak_ptr
    {
        /* ... */

      element_type*     _M_ptr;         // Contained pointer.
      __weak_count<_Lp>  _M_refcount;    // Reference counter.
    };

/// shared_ptr_base.h
  template<_Lock_policy _Lp>
    class __weak_count
    {
        /* ... */

      _Sp_counted_base<_Lp>*  _M_pi;
    };

和 shared_ptr 设计一样,weak_ptr 只是对 __weak_ptr 的封装,所有实现都在基类,常用的接口如下

reset

releases the ownership of the managed object (public member function)

swap

swaps the managed objects (public member function)

use_count

returns the number of

 

shared_ptr

 

objects that manage the object (public member function)

expired

checks whether the referenced object was already deleted (public member function)

lock

creates a

 

shared_ptr

 

that manages the referenced object (public member function)

owner_before

provides owner-based ordering of weak pointers (public member function)

2.1、__weak_count

只有一个数据成员 _M_pi,是 _Sp_counted_base 类型,和 __shared_count 一样

/// shared_ptr_base.h
  template<_Lock_policy _Lp>
    class __weak_count
    {
        /* ... */
    private:
      friend class __shared_count<_Lp>;
#if __cplusplus >= 202002L
      template<typename> friend class _Sp_atomic;
#endif

      _Sp_counted_base<_Lp>*  _M_pi;
    };

__weak_count 主要是对 _M_weak_add_ref() 和 _M_weak_release() 操作引用计数。

/// bits/shared_ptr.h
      __weak_count(const __shared_count<_Lp>& __r) noexcept
      : _M_pi(__r._M_pi)
      {
    if (_M_pi != nullptr)
      _M_pi->_M_weak_add_ref();
      }

      __weak_count(const __weak_count& __r) noexcept
      : _M_pi(__r._M_pi)
      {
    if (_M_pi != nullptr)
      _M_pi->_M_weak_add_ref();
      }

      __weak_count(__weak_count&& __r) noexcept
      : _M_pi(__r._M_pi)
      { __r._M_pi = nullptr; }

      ~__weak_count() noexcept
      {
    if (_M_pi != nullptr)
      _M_pi->_M_weak_release();
      }

      __weak_count&
      operator=(const __shared_count<_Lp>& __r) noexcept
      {
    _Sp_counted_base<_Lp>* __tmp = __r._M_pi;
    if (__tmp != nullptr)
      __tmp->_M_weak_add_ref();
    if (_M_pi != nullptr)
      _M_pi->_M_weak_release();
    _M_pi = __tmp;
    return *this;
      }

      __weak_count&
      operator=(const __weak_count& __r) noexcept
      {
    _Sp_counted_base<_Lp>* __tmp = __r._M_pi;
    if (__tmp != nullptr)
      __tmp->_M_weak_add_ref();
    if (_M_pi != nullptr)
      _M_pi->_M_weak_release();
    _M_pi = __tmp;
    return *this;
      }

      __weak_count&
      operator=(__weak_count&& __r) noexcept
      {
    if (_M_pi != nullptr)
      _M_pi->_M_weak_release();
    _M_pi = __r._M_pi;
        __r._M_pi = nullptr;
    return *this;
      }

      long
      _M_get_use_count() const noexcept
      { return _M_pi != nullptr ? _M_pi->_M_get_use_count() : 0; }

2.2 __weak_ptr

有两个数据域,一个存放对象指针,一个存放引用计数相关的结构。

/// shared_ptr_base.h
  template<typename _Tp, _Lock_policy _Lp>
    class __weak_ptr
    {
        /* ... */
      element_type*     _M_ptr;         // Contained pointer.
      __weak_count<_Lp>  _M_refcount;    // Reference counter.
    };

lock() 是为了提升为 __shared_ptr 对象

/// shared_ptr_base.h
      __shared_ptr<_Tp, _Lp>
      lock() const noexcept
      { return __shared_ptr<element_type, _Lp>(*this, std::nothrow); }

另外就是 _M_assign() 函数,__enable_shared_from_this 会使用它。可能比较好奇,为什么需要 use_count() 函数返回 0 才赋值。

/// shared_ptr_base.h
      // Used by __enable_shared_from_this.
      void
      _M_assign(_Tp* __ptr, const __shared_count<_Lp>& __refcount) noexcept
      {
    if (use_count() == 0)
      {
        _M_ptr = __ptr;
        _M_refcount = __refcount;
      }
      }

use_count() 是调用 _M_get_use_count() 函数,_M_get_use_count() 会判断 _M_pi 是否为空,为空直接返回 0。

/// shared_ptr_base.h
      long
      use_count() const noexcept
      { return _M_refcount._M_get_use_count(); }

use_count() 返回 0,表示 __weak_ptr 没有指向任何对象。

3、std::unique_ptr

拷贝赋值构造函数和赋值运算符是删除的(移动语义除外)

/// unique_ptr.h
  template <typename _Tp, typename _Dp = default_delete<_Tp>>
    class unique_ptr
    {

      unique_ptr& operator=(unique_ptr&&) = default;       

      template<typename _Up, typename _Ep>
    _GLIBCXX23_CONSTEXPR
        typename enable_if< __and_<
          __safe_conversion_up<_Up, _Ep>,
          is_assignable<deleter_type&, _Ep&&>
          >::value,
          unique_ptr&>::type
    operator=(unique_ptr<_Up, _Ep>&& __u) noexcept
    {
      reset(__u.release());
      get_deleter() = std::forward<_Ep>(__u.get_deleter());
      return *this;
    }

      /// Reset the %unique_ptr to empty, invoking the deleter if necessary.
      _GLIBCXX23_CONSTEXPR
      unique_ptr&
      operator=(nullptr_t) noexcept
      {
    reset();
    return *this;
      }

      // Disable copy from lvalue.
      unique_ptr(const unique_ptr&) = delete;
      unique_ptr& operator=(const unique_ptr&) = delete;
  };

析构函数释放对象

/// unique_ptr.h
      ~unique_ptr() noexcept
      {
    static_assert(__is_invocable<deleter_type&, pointer>::value,
              "unique_ptr's deleter must be invocable with a pointer");
    auto& __ptr = _M_t._M_ptr();
    if (__ptr != nullptr)
      get_deleter()(std::move(__ptr));
    __ptr = pointer();
      }

常用的接口如下:

release

returns a pointer to the managed object and releases the ownership (public member function)

reset

replaces the managed object (public member function)

swap

swaps the managed objects (public member function)

get

returns a pointer to the managed object (public member function)

get_deleter

returns the deleter that is used for destruction of the managed object (public member function)

operator bool

checks if there is an associated managed object (public member function)

operator*operator->

dereferences pointer to the managed object (public member function)

4、std::enable_shared_from_this

enable_shared_from_this 字如其名,“只从 this 指针构造一个 shared_ptr 对象”。当然,并不是直接用 this 指针,而是在一个类的(成员函数)内部,构造该类的 shared_ptr 对象,并且和已有 shared_ptr 共享状态。

比如如下代码,直接使用 this 指针构造一个 shared_ptr 对象,bad0 和 bad1 并不是共享状态。

struct Bad {
    std::shared_ptr<Bad> getptr() {
        return std::shared_ptr<Bad>(this);
    }
    ~Bad() { std::cout << "Bad::~Bad() called\n"; }
};

void testBad() {
    // Bad, each shared_ptr thinks it's the only owner of the object
    std::shared_ptr<Bad> bad0 = std::make_shared<Bad>();
    std::shared_ptr<Bad> bad1 = bad0->getptr();
    std::cout << "bad1.use_count() = " << bad1.use_count() << '\n';
} // UB: double-delete of Bad


int main() {
    testBad();
}

将出现 doule-free 问题。

Bad::~Bad() called
Bad::~Bad() called
*** glibc detected *** ./test: double free or corruption

enable_shared_from_this 就是为了解决这个问题,使得可以在类内部构造一个 shared_ptr 对象,和已经存在的 shared_ptr 共享状态。使用 enable_shared_from_this,我们可以这样实现

class Good : public std::enable_shared_from_this<Good> {
public:
    std::shared_ptr<Good> getptr() {
        return shared_from_this();
    }
};

void testGood() {
    // Good: the two shared_ptr's share the same object
    std::shared_ptr<Good> good0 = std::make_shared<Good>();
    std::shared_ptr<Good> good1 = good0->getptr();
    std::cout << "good1.use_count() = " << good1.use_count() << '\n';
}

int main() {
    testGood();
}

good1.user_count() 的值为 2,符合预期。

good1.use_count() = 2

enable_shared_from_this 是如何实现的呢?enable_shared_from_this 拥有一个 weak_ptr

/// shared_ptr_base.h
  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() { }

/* ... */

    private:
      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*
      __enable_shared_from_this_base(const __shared_count<>&,
                     const enable_shared_from_this* __p)
      { return __p; }

      template<typename, _Lock_policy>
    friend class __shared_ptr;

      mutable weak_ptr<_Tp>  _M_weak_this;
    };

比较好奇的是,_M_weak_this 什么时候初始化。需要回到 __shared_ptr 构造函数,会调用 _M_enable_shared_from_this_with() 函数。

如果某个类继承于 enable_shared_from_this,_M_enable_shared_from_this_with() 函数定义如下,调用

/// shared_ptr.h
      template<typename _Yp, typename _Yp2 = typename remove_cv<_Yp>::type>
    typename enable_if<__has_esft_base<_Yp2>::value>::type
    _M_enable_shared_from_this_with(_Yp* __p) noexcept
    {
      if (auto __base = __enable_shared_from_this_base(_M_refcount, __p))
        __base->_M_weak_assign(const_cast<_Yp2*>(__p), _M_refcount);
    }

如果没有继承 enable_shared_from_this,_M_enable_shared_from_this_with() 函数什么都不做。

/// shared_ptr_base.h
      template<typename _Yp, typename _Yp2 = typename remove_cv<_Yp>::type>
    typename enable_if<!__has_esft_base<_Yp2>::value>::type
    _M_enable_shared_from_this_with(_Yp*) noexcept
    { }

_M_weak_assign() 函数调用 __weak_ptr::_M_assign() 函数初始化。

/// share_ptr_base.h
    _M_weak_assign(_Tp1* __p, const __shared_count<>& __n) const noexcept
    { _M_weak_this._M_assign(__p, __n); }

shared_from_this() 函数就不言而喻了,从 weak_ptr 构造一个 shared_ptr 对象。

/// shared_ptr.h
      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_from_this() 返回 weak_ptr

/// shared_ptr.h
      weak_ptr<_Tp>
      weak_from_this() noexcept
      { return this->_M_weak_this; }

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

从 shared_from_this() 定义可以看到,如果 _M_weak_this 没有初始化,shared_from_this() 会出现错误,比如如下使用方式,shared_from_this() 会抛出异常。

void misuseGood() {
    // Bad: shared_from_this is called without having std::shared_ptr owning the caller
    try {
        Good not_so_good;
        std::shared_ptr<Good> gp1 = not_so_good.getptr();
    } catch(std::bad_weak_ptr& e) {
        // undefined behavior (until C++17) and std::bad_weak_ptr thrown (since C++17)
        std::cout << e.what() << '\n';
    }
}

更好的方法时将构造函数定义为私有,提供统一的创建方法,确保调用 shared_from_this() 之前,一定存在至少一个 shared_ptr 共享对象。

class Best : public std::enable_shared_from_this<Best> {
public:
    std::shared_ptr<Best> getptr() {
        return shared_from_this();
    }
    // No public constructor, only a factory function,
    // so there's no way to have getptr return nullptr.
    [[nodiscard]] static std::shared_ptr<Best> create() {
        // Not using std::make_shared<Best> because the c'tor is private.
        return std::shared_ptr<Best>(new Best());
    }
private:
    Best() = default;
};

void testBest() {
    // Best: Same but can't stack-allocate it:
    std::shared_ptr<Best> best0 = Best::create();
    std::shared_ptr<Best> best1 = best0->getptr();
    std::cout << "best1.use_count() = " << best1.use_count() << '\n';

    // Best stackBest; // <- Will not compile because Best::Best() is private.
}


int main() {
    testBest();
}
best1.use_count() = 2

5、std::make_shared()

调用 allocate_shared 构造一个 shared_ptr

/// bits/shared_ptr.h
  template<typename _Tp, typename... _Args>
    inline shared_ptr<_NonArray<_Tp>>
    make_shared(_Args&&... __args)
    {
      using _Alloc = allocator<void>;
      _Alloc __a;
      return shared_ptr<_Tp>(_Sp_alloc_shared_tag<_Alloc>{__a},
                 std::forward<_Args>(__args)...);
    }

6、shared_ptr 指针转换

创建新的 std::shared_ptr 的实例,将管理对象的类型从 _Tp1 转换成 _Tp。底层仍然共享管理的对象

/// bits/shared_ptr.h
  /// Convert type of `shared_ptr`, via `static_cast`
  template<typename _Tp, typename _Up>
    inline shared_ptr<_Tp>
    static_pointer_cast(const shared_ptr<_Up>& __r) noexcept
    {
      using _Sp = shared_ptr<_Tp>;
      return _Sp(__r, static_cast<typename _Sp::element_type*>(__r.get()));
    }

  /// Convert type of `shared_ptr`, via `const_cast`
  template<typename _Tp, typename _Up>
    inline shared_ptr<_Tp>
    const_pointer_cast(const shared_ptr<_Up>& __r) noexcept
    {
      using _Sp = shared_ptr<_Tp>;
      return _Sp(__r, const_cast<typename _Sp::element_type*>(__r.get()));
    }

  /// Convert type of `shared_ptr`, via `dynamic_cast`
  template<typename _Tp, typename _Up>
    inline shared_ptr<_Tp>
    dynamic_pointer_cast(const shared_ptr<_Up>& __r) noexcept
    {
      using _Sp = shared_ptr<_Tp>;
      if (auto* __p = dynamic_cast<typename _Sp::element_type*>(__r.get()))
    return _Sp(__r, __p);
      return _Sp();
    }

7、std::shared_ptr<void> 工作方式

下面的方式是可以正常工作的

class Foo {
 public:
  Foo(int val): val(val), next(nullptr) {
    std::cout << "Foo\n";
  }
  ~Foo() {
    std::cout << "~Foo\n";
  }
  int val;
  Foo* next;
};

struct Deleter {
  void operator()(Foo* p) const {
    std::cout << "Call delete from function object...\n";
    delete p;
  }
};

int main() {
  shared_ptr<void> ptr;
  ptr.reset(new Foo(-1));
  return 0;
}

即使定义的时候,std::shared_ptr 的类模板类型是 void 类型,我们在 reset() 函数中传入一个 Foo 类型的指针,std::shared_ptr 也可以自动地析构 Foo 的对象。如果是 std::shared_ptr<int> 没有这种用法。

shared_ptr<int> ptr;
ptr.reset(new Foo(-1)); // cannot convert ‘Foo*’ to ‘int*’ in initialization

根据分析的继承关系,shared_ptr 继承于 __shared_ptr,回头看一下 __shared_ptr 的实现

/// shared_ptr_base.h
  template<typename _Tp, _Lock_policy _Lp>
    class __shared_ptr
    : public __shared_ptr_access<_Tp, _Lp>
    {
    public:
     using element_type = typename remove_extent<_Tp>::type;

        /* ... */
      element_type*       _M_ptr;         // Contained pointer.
      __shared_count<_Lp>  _M_refcount;    // Reference counter.
    };

可以看到,__shared_ptr::_M_ptr 跟模板参数类型相关,而 __shared_ptr::_M_refcount 跟模板参数是无关的。所以当模板参数是 void 的时候,void 指针可以指向任何对象,而其他指针则不行。

根据前面的分析 _M_refcount 是负责释放管理的对象的,那即使定义为 std::shared_ptr<void>,也可以释放对象,它是如何做到的?在回头看一下 __shared_count 的定义

/// shared_ptr_base.h
  template<_Lock_policy _Lp>
    class __shared_count
    {
        /* ... */
      _Sp_counted_base<_Lp>*  _M_pi;
    };

_Sp_counted_base 是一个基类,只有两个表示引用计数的成员。如前面所说,_Sp_counted_base 的 _M_release() 会调用派生类的 _M_dispose() 进行对象的释放。并且 __shared_count 会根据不同的传入参数,创建不同的 _Sp_counted_base 对象。接下来分析三个派生类的构造函数。

首先是 _Sp_counted_ptr,_Sp_counted_deleter 和 _Sp_counted_ptr_inplace 三个派生类都是模板类,模板参数 _Ptr 就是实际管理的对象的类型指针。所以即使在定义 std::shared_ptr 指定类模板参数为 void。可以看到 reset() 函数也是模板函数

/// shared_ptr_base.h
      template<typename _Yp>
    _SafeConv<_Yp>
    reset(_Yp* __p) // _Yp must be complete.
    {
      // Catch self-reset errors.
      __glibcxx_assert(__p == nullptr || __p != _M_ptr);
      __shared_ptr(__p).swap(*this);
    }

      template<typename _Yp, typename _Deleter>
    _SafeConv<_Yp>
    reset(_Yp* __p, _Deleter __d)
    { __shared_ptr(__p, std::move(__d)).swap(*this); }

      template<typename _Yp, typename _Deleter, typename _Alloc>
    _SafeConv<_Yp>
    reset(_Yp* __p, _Deleter __d, _Alloc __a)
        { __shared_ptr(__p, std::move(__d), std::move(__a)).swap(*this); }

不仅如此,__shared_ptr、__shared_count 的有参构造函数都是模板函数。所以通过模板推断,可以推断出 reset() 传入指针的类型,然后传入相应的派生类,因此可以正常析构。

欢迎关注 “源知源为”,阅读更多技术干货
#C++11##智能指针##23届找工作求助阵地#
C/C++基础 文章被收录于专栏

C/C++ 语言基础

全部评论

相关推荐

头像 会员标识
昨天 17:08
已编辑
牛客_产品运营部_私域运营
腾讯 普通offer 24k~26k * 15,年包在36w~39w左右。
点赞 评论 收藏
分享
斑驳不同:还为啥暴躁 假的不骂你骂谁啊
点赞 评论 收藏
分享
3 3 评论
分享
牛客网
牛客企业服务