[英]Why can't std::atomic<T> be swapped?
#include <atomic>
int main()
{
auto a = std::atomic_int(1);
auto b = std::atomic_int(2);
std::swap(a, b); // error
}
error message:错误信息:
error: no matching function for call to 'swap(std::atomic&, std::atomic&)'错误:没有匹配的 function 调用 'swap(std::atomic&, std::atomic&)'
Why can't std::atomic<T>
be swapped?为什么不能交换std::atomic<T>
?
std::atomic
has a deleted copy constructor, and doesn't have a move construtor. std::atomic
有一个已删除的复制构造函数,并且没有移动构造函数。
Therefore it is neither move assignable nor move constructible .因此它既不是move assignable也不是move constructible 。
Therefore std::swap
cannot be called on any std::atomic
type.因此std::swap
不能在任何std::atomic
类型上调用。
Reference:参考:
https://en.cppreference.com/w/cpp/algorithm/swap https://en.cppreference.com/w/cpp/algorithm/swap
There are two levels to that issue.这个问题有两个层面。
First is plain simple and technical - std::atomic
is not move constructible or move assignable as mentioned in other answer.首先是简单且技术性的 - std::atomic
不可移动构造或移动可分配,如其他答案中所述。
Second is the rationale behind this - swapping std::atomic
s would not be atomic in itself.其次是这背后的基本原理——交换std::atomic
本身并不是原子的。 And since std::atomic
s are used in multithreaded environments adding swap
would have lead to wide range of bugs due to possible misunderstandings (that since there is swap
for std::atomic
then it is atomic in itself).并且由于std::atomic
在多线程环境中使用,添加swap
会由于可能的误解而导致广泛的错误(因为std::atomic
有swap
,所以它本身就是原子的)。
All in all - if you don't need atomic swap
this can be pretty easily done using mentioned exchange
s.总而言之——如果你不需要原子swap
,这可以很容易地使用提到的exchange
来完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.