Reference counting of smart pointer shared_ptr

    Previous Article  🔗 smart pointer unique_ptr Introduced unique_ptr, and the main difference between shared_ptr and unique_ptr is that multiple shared_ptr can manage the same object, which is realized through copy constructor and reference counting mechanism.

shared_ptr(const std::__1::shared_ptr<_Tp> &);
shared_ptr(std::__1::shared_ptr<_Tp> &&);
std::__1::shared_ptr<_Tp> & operator=(const std::__1::shared_ptr<_Tp> &);
std::__1::shared_ptr<_Tp> & operator=(std::__1::shared_ptr<_Tp> &&);

It can be seen that the constructor not only supports rvalue parameter passing, but also supports lvalue. As for the reference count, there should be a data member to record the number of references. First look at the definition of shared_ptr:

template<class _Tp>
class _LIBCPP_SHARED_PTR_TRIVIAL_ABI _LIBCPP_TEMPLATE_VIS shared_ptr
{
    ...
private:
    _Tp*      __ptr_;
    __shared_weak_count* __cntrl_;
    ...
}

There are only two data members, of which __ptr_ seems to point to a native pointer, and the other one has a high probability of saving information related to reference counting, but it is of type __shared_weak_count, which is actually a class:

class _LIBCPP_TYPE_VIS __shared_weak_count
    : private __shared_count
{
    long __shared_weak_owners_;

public:
    _LIBCPP_INLINE_VISIBILITY
    explicit __shared_weak_count(long __refs = 0) _NOEXCEPT
        : __shared_count(__refs),
          __shared_weak_owners_(__refs) {}
    ...
}

It has only one data member __shared_weak_owners_, but it can be seen from the name that it corresponds to the smart pointer weak_ptr, but it also privately inherits the class __shared_count:

class _LIBCPP_TYPE_VIS __shared_count
{
    ...
protected:
    long __shared_owners_;
    ...

public:
    _LIBCPP_INLINE_VISIBILITY
    explicit __shared_count(long __refs = 0) _NOEXCEPT
        : __shared_owners_(__refs) {}
    ...
}

Its data member __shared_owners_ is used for the record reference count we are looking for, but its initial value is 0, and when the use_count() method is called, it returns 1, and see the call chain:

// shared_ptr
long use_count() const _NOEXCEPT {
    return __cntrl_ ? __cntrl_->use_count() : 0;
}
// __shared_weak_count
long use_count() const _NOEXCEPT {
    return __shared_count::use_count();
}
// __shared_count
long use_count() const _NOEXCEPT {
    return __libcpp_relaxed_load(&__shared_owners_) + 1;
}

At this point, it is clear that the returned reference number is processed by adding 1 in the program. As for why this is done, I have not thought of any reasonable explanation so far. If anyone knows it, please give me some pointers!

So how does that affect reference counting? For example, the following code:

{
    shared_ptr<A> s (new A(5));
    cout << "s count:" << s.use_count() << endl;
    shared_ptr<A> t(s);
    cout << "t count:" << t.use_count() << endl;
    s.reset();
    cout << "t count:" << t.use_count() << endl;
}

The output after running is as follows:

s count:1
t count:2
t count:1

Here we have to look at the implementation of the copy constructor of shared_ptr:

// shared_ptr
template<class _Tp>
inline
shared_ptr<_Tp>::shared_ptr(const shared_ptr& __r) _NOEXCEPT
    : __ptr_(__r.__ptr_), __cntrl_(__r.__cntrl_)
{
    if (__cntrl_)
        __cntrl_->__add_shared();
}
// __shared_weak_count
void __add_shared() _NOEXCEPT {
  __shared_count::__add_shared();
}

// __shared_count
void __add_shared() _NOEXCEPT {
  __libcpp_atomic_refcount_increment(__shared_owners_);
}

Follow along the way and finally call the __add_shared() method in the class __shared_count. Note that the __libcpp_atomic_refcount_increment() method is used here to ensure the atomicity of the count. Let's see how reset() releases and decrements the current count by 1.

template<class _Tp>
inline
void
shared_ptr<_Tp>::reset() _NOEXCEPT
{
    shared_ptr().swap(*this);
}

First, the constructor shared_ptr() is called to generate an anonymous empty shared_ptr pointer, and then the swap() method is called to exchange with the current object, which is the smart pointer s.

swap(_Tp& __x, _Tp& __y) _NOEXCEPT_(is_nothrow_move_constructible<_Tp>::value &&
                                    is_nothrow_move_assignable<_Tp>::value)
{
    _Tp __t(_VSTD::move(__x));
    __x = _VSTD::move(__y);
    __y = _VSTD::move(__t);
}

The exchange here is not a simple assignment exchange, but the introduction of move semantics, so that the anonymous shared_ptr pointer just generated becomes the smart pointer s to be released. When the reset() method code block is exited after swapping, the destructor is automatically executed:

// shared_ptr
template<class _Tp>
shared_ptr<_Tp>::~shared_ptr()
{
    if (__cntrl_)
        __cntrl_->__release_shared();
}
// __shared_weak_count
void __release_shared() _NOEXCEPT {
    if (__shared_count::__release_shared())
        __release_weak();
}
// __shared_count
bool __release_shared() _NOEXCEPT {
    if (__libcpp_atomic_refcount_decrement(__shared_owners_) == -1) {
        __on_zero_shared();
        return true;
    }
    return false;
}

In the end, the __release_shared() method in the class __shared_count is called to atomically decrement it by 1, but there is an additional judgment compared to adding 1, that is, when there is no shared_ptr pointer pointing to the object, the __on_zero_shared() method must be called.

// __shared_ptr_pointer
template <class _Tp, class _Dp, class _Alloc>
void
__shared_ptr_pointer<_Tp, _Dp, _Alloc>::__on_zero_shared() _NOEXCEPT
{
    __data_.first().second()(__data_.first().first());
    __data_.first().second().~_Dp();
}

This method is a member function of the class __shared_ptr_pointer, which seems a bit sudden, but if you look at how the constructor of shared_ptr is implemented, you will know.

template<class _Tp>
template<class _Yp>
shared_ptr<_Tp>::shared_ptr(_Yp* __p,
                            typename enable_if<__compatible_with<_Yp, element_type>::value, __nat>::type)
    : __ptr_(__p)
{
    unique_ptr<_Yp> __hold(__p);
    typedef typename __shared_ptr_default_allocator<_Yp>::type _AllocT;
    typedef __shared_ptr_pointer<_Yp*, __shared_ptr_default_delete<_Tp, _Yp>, _AllocT > _CntrlBlk;
    __cntrl_ = new _CntrlBlk(__p, __shared_ptr_default_delete<_Tp, _Yp>(), _AllocT());
    __hold.release();
    __enable_weak_this(__p, __p);
}

__cntrl_ is actually a __shared_ptr_pointer class object, and this class inherits from __shared_weak_count:

template <class _Tp, class _Dp, class _Alloc>
class __shared_ptr_pointer
    : public __shared_weak_count
{
    __compressed_pair<__compressed_pair<_Tp, _Dp>, _Alloc> __data_;
public:
    _LIBCPP_INLINE_VISIBILITY
    __shared_ptr_pointer(_Tp __p, _Dp __d, _Alloc __a)
        :  __data_(__compressed_pair<_Tp, _Dp>(__p, _VSTD::move(__d)), _VSTD::move(__a)) {}
    ...
};

But the class __shared_weak_count is an abstract class because it has a pure virtual member function:

private:
    virtual void __on_zero_shared_weak() _NOEXCEPT = 0;

So actually the class __shared_ptr_pointer manages the allocation and destruction of shared_ptr memory.

So far, the reference counting part of shared_ptr is almost introduced. Throughout the article, I feel that it is more of a description. I can only say that I know a general idea, but I still lack some understanding of my own. I hope that I will have the opportunity to understand this in depth in the future.

Tags: C++

Posted by creatives on Fri, 23 Dec 2022 21:12:22 +0300