为什么不能对换std::atomic<T>?

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: no matching function for call to 'swap(std::atomic&, std::atomic&)'

为什么std::atomic<T>不能互换?

std::atomic 有删除的复制构造函数,没有移动构造函数。

因此它既不是移动可分配的也不是移动可构造的

因此 std::swap 无法在任何 std::atomic 类型上调用。

参考:

https://en.cppreference.com/w/cpp/algorithm/swap

这个问题有两个层次。

首先是简单和技术性的 - std::atomic 不是其他答案中提到的移动可构造或移动可分配。

其次是这背后的基本原理——交换 std::atomics 本身并不是原子的。由于 std::atomics 在多线程环境中使用,添加 swap 会由于可能的误解而导致广泛的错误(因为 std::atomicswap 那么它是原子本身)。

总而言之 - 如果你不需要原子 swap 这可以使用提到的 exchanges 很容易地完成。