c++ - C++ 是否提供线程安全的引用计数器?

标签 c++ reference-counting

标准 C++ 库中是否有线程安全的引用计数器类(或作为 Visual Studio 中的扩展),或者我是否需要从头开始编写这种对象?
我希望有一个纯粹执行引用计数的对象 shared_ptr可能,除了它可以准确地跨多个线程执行此操作,并且无需管理任何内容。 shared_ptr它的表亲结构很好,因为它们定义了您需要的所有复制构造函数和赋值运算符,这些……对我来说是 C++ 中最容易出错的部分; C++ 构造函数之于 C++,就像 Kick-off 之于美式足球。

struct Fun {

    // this member behaves in a way I appreciate, save for 2 short-comings:
    // - needless allocation event (minor)
    // - ref counting is only estimate if shared across threads (major)
    std::shared_ptr<int> smartPtr {new int};  

    // this is the hypothetical object that I'm searching for
    // + allocates only a control block for the ref count
    // + refCount.unique() respects reality when refs exist across many threads
    //   I can always count on this being the last reference
    std::object_of_desire refCount;

    // no explicit copy constructors or assignment operators necessary
    // + both members of this class provide this paperwork for me, 
    //   so I can careless toss this Fun object around and it'll move
    //   as one would expect, making only shallow copies/moves and ref counting
    Fun(); 

    ~Fun(){
        if(refCount.unique()){
             smart_assert("I swear refCount truly is unique, on pain of death");
        }
    }
}

最佳答案

关于线程安全的警告 w.r.t. std::shared_ptr

  • 如果您有多个线程可以访问同一个指针对象,那么如果其中一个线程修改了指针,就会发生数据竞争。如果每个线程都有自己的实例,指向相同的共享状态,则共享状态上没有数据竞争。
  • 线程上指向对象的最终修改不inter-thread happens before另一个线程观察 use_count of 1. 如果没有修改指向的对象,则指向的对象上不存在数据竞争。

  • 这是您想要的类型
    class ref_count {
    public:
        bool unique() const { return ptr.use_count() == 1; }
    private:
        struct empty {};
        std::shared_ptr<empty> ptr = std::make_shared<empty>();
    };
    

    关于c++ - C++ 是否提供线程安全的引用计数器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68935996/

    相关文章:

    rust - 为什么打开克隆的 Rc 会引起 panic ?

    c++ - 在 std::cout 中使用单引号打印字符串实际上打印的是数字

    c++ - 如何连接 LPCWSTR 和 char[]?

    delphi - 为什么我的 Delphi 对象没有调用 _AddRef 和 _Release?

    algorithm - 收集循环的引用计数最简单的增强是什么?

    ios - Objective-C 如何高效地进行引用计数?

    objective-c - 是否在(保留)正确的@property 上分配 self.string = @""?

    c++ - 变量或字段 'name of var'声明为void

    c++ - 在 visual c++ 的 Release 模式下使用的 boost 调试库

    c++ - 非重写虚函数的绑定(bind)类型