【发布时间】:2020-05-07 11:20:19
【问题描述】:
#include <atomic>
int main()
{
auto a = std::atomic_int(1);
auto b = std::atomic_int(2);
std::swap(a, b); // error
}
错误信息:
错误:没有匹配函数调用 'swap(std::atomic&, std::atomic&)'
为什么不能交换std::atomic<T>?
【问题讨论】:
-
通过
std::swap交换不会是原子的,但我想知道为什么它没有成员swap... -
交换它们时不需要是原子的。
-
相关? Atomic exchange of two std::atomic<T*> objects in a lock-free manner in C++11?; “问题是不可能跨两个原子对象进行原子操作,[...]”.
-
当
atomic不需要是原子的时候,为什么要首先使用它?考虑两个线程同时交换。单独的读写是原子的,但是交换后的结果可能会搞砸 -
例如在 move-ctor 中,成员变量是原子的。 @idclev463035818
标签: c++ c++11 std standards atomic