stl1weekend icon indicating copy to clipboard operation
stl1weekend copied to clipboard

关于sharedptr thread-safe实现的问题

Open CS-liujf opened this issue 5 months ago • 15 comments

sharedptr引用计数减被封装成如下的函数

void _M_decref() noexcept {
        if (_M_refcnt.fetch_sub(1, std::memory_order_relaxed) == 1) {
            delete this;
        }
    }

该if块先判断原始引用计数是否等于1,如果为真则进行delete。然而判断和delete是两个操作,并不是一个原子操作。是否存在这样一种情况:判断条件成立,但在delete前有其它线程给引用计数+1?此时进行delete就出错了吧

CS-liujf avatar Sep 06 '24 01:09 CS-liujf