Why does the atomic_flag default constructor leave the state unspecified?

When using std::atomic_flag must be taken to always explicitly initialize it using ATOMIC_FLAG_INIT , which is error prone. However, there is a default constructor ... So, is there an objective reason why the default constructor leaves the flag in an undefined state?

+8
source share
2 answers

This link (posted by dyp in the comments) describes that this decision was made, because on some architectures a zero initialized atomic_flag will correspond to a given state, and on some it will correspond to a cleared state. Because of this, it was determined that atomic_flag , which is not explicitly initialized with ATOMIC_FLAG_INIT , is initially in an undefined state.

+3
source

This answer has already been answered by this answer.

I asked this problem to come up with a map with a tuple containing std::atomic_flag , and adding explicit initialization easily adds a lot of complex code.

A workaround is to simply wrap it in another type, such as this one:

 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 do not need to worry about initialization (except for some special cases, such as static init fiasco).

0
source

Source: https://habr.com/ru/post/1243567/


All Articles