c++ - std::atomic_flag 作为成员变量

标签 c++ c++11

在类构造函数中初始化 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 type atomic_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 an atomic_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/

相关文章:

c++ - 意外的输出

c++ - 在 C++11 中,如何获取没有名称的临时左值?

c++ - C++11 中的最终枚举类

构造函数中的c++异常安全

c++ - Eigen 矩阵和 vector 之上的抽象类

c++ - 通过带有Visual Studio 2015的NuGet包的OpenCV,如何配置?

c++ - C++ 中的 union 和按位运算

c++ - 从 C++ dll 调用 delphi 应用程序中的函数

c - 获取嵌入式 PACKED_STRUCT 定义以在 g++ 下编译

c++ - 在 lambda 函数中使用 auto self(shared_from_this()) 变量的原因是什么?