[英]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.在我的 class 中,我想要一个
std::array<std::atomic<bool>>
,我想在构造函数中通过成员初始化来初始化它。
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>&)'
可悲的是,这不起作用,给出:
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.这是有道理的,因为
std::atomic<bool>
既不可复制也不可移动。
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这是一个实时代码链接: https://godbolt.org/z/fEsfaWGcn
You can use an initializer-list for each item in the initializer list of the std::array
.您可以为
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).虽然语法有点奇怪,但效果很好(在 GCC、Clang、MSVC 和 ICC 上测试)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.