简体   繁体   中英

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?

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::atomic s would not be atomic in itself. And since std::atomic s 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 exchange s.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM