标准 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
是
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/