c++ - 什么是 ATOMIC_FLAG_INIT 以及它应该如何使用?

标签 c++ c++17 atomic

示例代码来自 ATOMIC_FLAG_INIT on cppreference

#include <atomic>

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
}

这是否意味着依赖“零初始化”是未指定的? 我们是否应该始终使用此定义进行初始化?为什么 ?

最佳答案

Does this imply that relying on zero initialization for example is unspecified?

您可能指的是值初始化,答案是肯定的,它是未指定的,如标准中所写:http://eel.is/c++draft/atomics.flag#4.sentence-5 .

Are we supposed to always initialize using this define?

是的。上面链接的句子暗示。

Why?

因为标准要求它。正如在 this question 中讨论的那样, std::atomic_flag不用于一般用途,它是用于构建其他原语的低级原语。

对于一般用途,请使用 std::atomic<bool> .

关于c++ - 什么是 ATOMIC_FLAG_INIT 以及它应该如何使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57551937/

相关文章:

c++ - 内联汇编 (__asm) block 是否会阻止功能优化?

c++ - 如何为 nvcc 添加预定义宏?

c++ - 获取 C++17/C++20 中参数包的最后一个元素

c++ - 范围和分解的原因不允许constexpr

c++ - 为什么在引用计数器上需要存储顺序限制?

c++ - 使用 boost::pool 管理 std::vector 中的内存分配

c++ - 比较身份引用的标准方法

c++ - 使用 C++17 检测类成员是否存在

java - 为什么某些原始类型缺少原子版本而某些原始类型存在?

c++ - 从 C++ 中的另一个线程读取指针