【问题标题】:Why counter in std::shared_ptr is atomic?为什么 std::shared_ptr 中的计数器是原子的?
【发布时间】:2022-07-26 16:39:15
【问题描述】:

_Sp_counted_base 的实现使用原子计数器:

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

为什么计数器是原子的,而 ptr 不是?需要自动计数吗?有没有必要的例子?

(因为 std::shared_ptr 不是线程安全的,所以我认为不需要原子计数)

【问题讨论】:

  • std::shared_ptr 线程安全

标签: c++ shared-ptr


【解决方案1】:

std::shared_ptr 从 C++11(添加它的标准)开始支持原子操作。 See the documentation.

【讨论】:

    猜你喜欢
    • 2020-10-28
    • 1970-01-01
    • 2013-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-20
    相关资源
    最近更新 更多