Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 763
xmllmx Avatar asked Jan 01 '23 02:01

xmllmx


2 Answers

std::atomic has a deleted copy constructor, and doesn't have a move construtor.

Therefore it is neither move assignable nor move constructible.

Therefore std::swap cannot be called on any std::atomic type.

Reference:

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

like image 85
Bathsheba Avatar answered Jan 05 '23 06:01

Bathsheba


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.

like image 34
bartop Avatar answered Jan 05 '23 06:01

bartop