c++automatic-ref-countingsmart-pointersinteger-overflowrefcounting

How do reference-counting smart pointer's avoid or handle reference-counter overflows?


In a naive reference-counting smart pointer implementation, the reference-counter could overflow. How is this overflow avoided or handled in C++ standard library implementations?


Solution

  • Snippets from stdlibc++ headers:

    typedef int _Atomic_word;
    
    class _Sp_counted_base
        /*snip*/
        _Atomic_word  _M_use_count;
        /*snip*/
        _M_weak_add_ref()
        { __gnu_cxx::__atomic_add_dispatch(&_M_weak_count, 1); }
    
    /*snip*/
    __atomic_add_dispatch(/*snip*/)
    {
        /*snip*/
        __atomic_add_single(/*snip*/);
        /*snip*/
    }
    
    __atomic_add_single(/*snip*/)
    { *__mem += __val; }
    

    Conclusion: This particular implementation "handles" reference-counter overflow by ignoring the possibility.