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

What is ATOMIC_FLAG_INIT and how is it supposed to be used?

示例代码来自 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
}

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

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

您的意思可能是 value-initialization,答案是肯定的,它是未指定的,如标准中所写: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>