简体   繁体   中英

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

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).

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