darune
darune

Reputation: 10972

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

Example code from 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 ? Are we supposed to always initialize using this define ? why ?

Upvotes: 1

Views: 531

Answers (1)

Daniel Langr
Daniel Langr

Reputation: 23497

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

You likely meant value-initialization, and the answer is yes, it is unspecified, as written in the Standard: http://eel.is/c++draft/atomics.flag#4.sentence-5.

Are we supposed to always initialize using this define?

Yes. The sentence linked above implies that.

Why?

Because the Standard demands it. As discussed in this question, std::atomic_flag is not for general use, it's rather a low-level primitive for building other primitives.

For generic use, use std::atomic<bool>.

Upvotes: 1

Related Questions