为什么有 shared_ptr
的原子重载,如 here 所述而不是为处理 shared_ptr
的 std::atomic
专门化。似乎与其余 C++ 标准库采用的面向对象模式不一致。
在使用 shared_ptr
实现 read copy update idiom 时,为了确保我做对了我们需要通过这些函数对共享指针进行所有访问(读取和写入)吗?
最佳答案
因为:
std::atomic may be instantiated with any TriviallyCopyable type T.
来源:http://en.cppreference.com/w/cpp/atomic/atomic
和
std::is_trivially_copyable<std::shared_ptr<int>>::value == false;
因此,您无法实例化 std::atomic<>
与 std::shared_ptr<>
.但是,自动内存管理在多线程中很有用,因此提供了这些重载。然而,这些重载很可能不是无锁的(首先使用 std::atomic<>
的一大吸引力);他们可能使用锁来提供同步性。
关于你的第二个问题:是的。
关于c++ - 为什么存在 shared_ptr 的原子重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38112882/