Search code examples
c++c++11stdstandardsatomic

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&)'

Why can't std::atomic<T> be swapped?


Solution

  • 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.

    Second is the rationale behind this - swapping std::atomics would not be atomic in itself. And since std::atomics 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).

    All in all - if you don't need atomic swap this can be pretty easily done using mentioned exchanges.