Synxis
Synxis

Reputation: 9388

Why atomic_flag default constructor leaves state unspecified?

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 ?

Upvotes: 8

Views: 394

Answers (2)

darune
darune

Reputation: 10962

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

Upvotes: 0

VLL
VLL

Reputation: 10155

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.

Upvotes: 3

Related Questions