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

xml*_*lmx 4 c++ standards std atomicity c++11

#include <atomic>

int main()
{
    auto a = std::atomic_int(1);
    auto b = std::atomic_int(2);

    std::swap(a, b); // error
}
Run Code Online (Sandbox Code Playgroud)

错误信息:

错误:没有用于调用“swap(std::atomic&, std::atomic&)”的匹配函数

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

Bat*_*eba 5

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

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

因此std::swap不能在任何std::atomic类型上调用。

参考:

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