Search code examples
c++stdatomicstdarray

How to initialize std::array<std::atomic<bool>> — no copy or move ctors


In my class, I want a std::array<std::atomic<bool>>, and I'd like to initialize it via member initialization, in the constructor.

For example:

struct Foo {

    Foo()
    : flags{{
        true,
        true
    }}
    { /* no op */ }
    std::array<std::atomic<bool>, 2> flags;
};

Sadly, this does not work, giving: error: use of deleted function 'std::atomic<bool>::atomic(const std::atomic<bool>&)'

This makes sense, because std::atomic<bool> is neither copyable nor movable.

So, somehow, I need to direct-initialize these two flags.

But what's the syntax for it?

Here is a live code link: https://godbolt.org/z/fEsfaWGcn


Solution

  • You can use an initializer-list for each item in the initializer list of the std::array. Here is how:

    struct Foo {
        Foo()
        : flags{{
            {true},
            {true}
        }}
        { /* no op */ }
        std::array<std::atomic<bool>, 2> flags;
    };
    

    While the syntax is a bit strange, it works well (tested on GCC, Clang, MSVC and ICC).