#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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With