I cannot figure out how to create the following:
std::pair<std::atomic<bool>, int>
I always invariably get
/usr/include/c++/5.5.0/bits/stl_pair.h:139:45: error: use of deleted function 'std::atomic::atomic(const std::atomic&)'
: first(__x), second(std::forward<_U2>(__y)) { }
I've tried
std::pair<std::atomic<bool>, int> pair = std::make_pair(true, 1); //doesn't work
std::pair<std::atomic<bool>, int> pair = std::make_pair({true}, 1); //doesn't work
std::pair<std::atomic<bool>, int> pair = std::make_pair(std::atomic<bool>(true), 1); //doesn't work
std::pair<std::atomic<bool>, int> pair = std::make_pair(std::move(std::atomic<bool>(true)), 1); //doesn't work
I know std::atomic is non-copyable, so how are you supposed to create it in a pair? Is it just not possible?
Each instantiation and full specialization of the std::atomic template defines an atomic type. Objects of atomic types are the only C++ objects that are free from data races; that is, if one thread writes to an atomic object while another thread reads from it, the behavior is well-defined.
std::pair is a class template that provides a way to store two heterogeneous objects as a single unit. A pair is a specific case of a std::tuple with two elements.
In order to solve this problem, C++ offers atomic variables that are thread-safe. The atomic type is implemented using mutex locks. If one thread acquires the mutex lock, then no other thread can acquire it until it is released by that particular thread.
You can do:
std::pair<std::atomic<bool>, int> p(true, 1);
This uses true
to initialize the atomic first member, without any extraneous copies or moves. In C++17, guaranteed copy elision also allows you to write:
auto p = std::pair<std::atomic<bool>, int>(true, 1);
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