1

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 ?

darune
  • 10,480
  • 2
  • 24
  • 62
  • Have you read the page you linked? It's directly there: _the value held after any other initialization is unspecified_. The same statement in the Standard: http://eel.is/c++draft/atomics.flag#4.sentence-5. – Daniel Langr Aug 19 '19 at 07:14
  • @DanielLangr I did read it - which is why I ask – darune Aug 19 '19 at 07:17
  • See this question: https://stackoverflow.com/q/17883703/580083. – Daniel Langr Aug 19 '19 at 07:19
  • @DanielLangr Thank you, that question is on the same topic - but OP there is just testing it wrong - not the issue here. – darune Aug 19 '19 at 07:23

1 Answers1

1

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>.

Daniel Langr
  • 22,196
  • 3
  • 50
  • 93
  • This almost answers my question. However "Because the Standard demands it" is not really a satisfying explaination. – darune Aug 19 '19 at 07:28
  • But perhaps this should be asked in a seperate question. – darune Aug 19 '19 at 07:29
  • 1
    @daurune It has been asked already here: https://stackoverflow.com/questions/35550947/why-atomic-flag-default-constructor-leaves-state-unspecified. This, in fact, makes your question a duplicate, so I would suggest to delete this one. – Daniel Langr Aug 19 '19 at 07:36