在类构造函数中初始化 std::atomic_flag
的安全方法是什么?
This question似乎在问我问的同一个问题 - 除了这里提问者提示编译器问题。
我的问题与 C++ 标准本身有关。根据this site ,未指定使用构造函数初始化器语法初始化 std::atomic_flag
。
std::atomic_flag static_flag = ATOMIC_FLAG_INIT; // static initialization,
// guaranteed to be available during dynamic initialization of static objects.
int main()
{
std::atomic_flag automatic_flag = ATOMIC_FLAG_INIT; // guaranteed to work
// std::atomic_flag another_flag(ATOMIC_FLAG_INIT); // unspecified
}
这些信息正确吗?如果是这样,我假设:
struct Foo
{
Foo() : flag(ATOMIC_FLAG_INIT)
{ }
std::atomic_flag flag;
};
...也未指定。那么,这是否意味着我们不能使用 std::atomic_flag
作为类的成员变量?或者,如果我们在类构造函数中简单地调用 std::atomic_flag::clear()
是否安全?
最佳答案
关于使用 ATOMIC_FLAG_INIT
的措辞自 N3337 到 N3936(当前的 C++14 草案)以来已更改。前者显示了 ATOMIC_FLAG_INIT
在复制初始化上下文中的可能用法。示例中的宏是非规范性的,并且没有提及在其他初始化上下文中使用的任何内容。
N3936 对用法进行了澄清,不再列举复制初始化的用法作为示例,而是作为描述本身的一部分。
§29.7/4 [atomics.flag]
The macro
ATOMIC_FLAG_INIT
shall be defined in such a way that it can be used to initialize an object of typeatomic_flag
to the clear state. The macro can be used in the form:atomic_flag guard = ATOMIC_FLAG_INIT;
It is unspecified whether the macro can be used in other initialization contexts. For a complete static-duration object, that initialization shall be static. Unless initialized with
ATOMIC_FLAG_INIT
, it is unspecified whether anatomic_flag
object has an initial state of set or clear.
讨论了这些更改的基本原理here .
所以你是对的,不能依赖在成员初始化列表中使用宏。解决方案是使用非静态数据成员初始化程序或 brace-or-equal-initializer 来初始化 atomic_flag
.然后它将在复制初始化上下文中进行初始化。
struct Foo
{
std::atomic_flag flag = ATOMIC_FLAG_INIT;
};
关于c++ - std::atomic_flag 作为成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24437396/