gpt4 book ai didi

c++ - 使用 shared_ptr 的内部指针的操作是原子的吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:14:25 25 4
gpt4 key购买 nike

同时复制和重置 shared_ptr 是否安全?

即考虑下面的代码

// Main thread (before creating any other threads)
shared_ptr<A> a(new A(1));

// Thread 1
shared_ptr<A> a_copy = a;

// Thread 2
a.reset(new(A(2));

其中线程 1 和 2 并行运行。我可以确定 a_copy 将存储指向较旧的 A(1) 或较新的 A(2) 共享对象的指针吗?

最佳答案

来自 cppreference :

All member functions (including copy constructor and copy assignment) can be called by multiple threads on different instances of shared_ptr without additional synchronization even if these instances are copies and share ownership of the same object.

所以,答案是否定的——这些操作不是线程安全的,因为复制和重置都应用于同一个实例,a。结果是数据竞争,导致未定义的行为。

关于c++ - 使用 shared_ptr 的内部指针的操作是原子的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31913558/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com