Search code examples
c++stdatomicstd-pairstdatomic

How do you create a std::pair containing a std::atomic?


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?


Solution

  • 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);