8

When using std::atomic_flag, one has to be careful to always explicitely initialize it using ATOMIC_FLAG_INIT, which is error-prone. However there is a default constructor... So, is there an objective reason behind having a default constructor leaving the flag in an unspecifiate state ?

Synxis
  • 9,236
  • 2
  • 42
  • 64
  • AFAIK, the default constructor is guaranteed to initialize the variable with 0 but it is not specified whether 0 refers to “clear” or “set”. Of course, this raises more questions than it answers… – 5gon12eder Feb 22 '16 at 10:22
  • 1
    Sadly, this is not even the case, according to cppreference: *[ATOMIC_FLAG_INIT] is the only way to initialize std::atomic_flag to a definite value: the value held after any other initialization is unspecified.*. But I guess it is possible to see it your way... – Synxis Feb 22 '16 at 10:26
  • 2
    http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1379.htm – dyp Feb 22 '16 at 11:57
  • 1
    Typical ISO lossage, it can only ever arrive at consensus by making everybody equally unhappy. – Hans Passant Feb 22 '16 at 12:37
  • 1
    @dyp That's a good source. I think the reasoning exposed here is broken, but it is perfectly acceptable as a answer to my question. If you post it I would upvote it. – Synxis Feb 22 '16 at 13:21

2 Answers2

3

This link (posted by dyp in comments), describes that this decision was made because on some architectures a zero-initialized atomic_flag would correspond to a set state, and on some it would correspond to a cleared state. Because of this, it was defined that an atomic_flag that is not explicitly initialized with ATOMIC_FLAG_INIT is initially in an indeterminate state.

Community
  • 1
  • 1
VLL
  • 9,634
  • 1
  • 29
  • 54
0

This question was already answered by this answer

I had this issue come up with a map that contained a tuple that contained an std::atomic_flag - and putting in explicit initalization easily adds a lot of complicated code.

A workaround solution is to just wrap it in another type, such as this:

struct atomic_flag_ : public std::atomic_flag {

    atomic_flag_() : std::atomic_flag{ ATOMIC_FLAG_INIT } {
    }

};

or without inheritance:

struct atomic_flag_ {

    std::atomic_flag flag{ ATOMIC_FLAG_INIT };

};

Now you don't have to worry about initalization (except in some special corner cases, like static init fiasco).

darune
  • 10,480
  • 2
  • 24
  • 62
  • It might be better idea to use `std::atomic_bool`, since in practice it would be lock free as well: https://stackoverflow.com/questions/10106936/are-atomic-variables-lock-free – VLL Aug 19 '19 at 08:49