Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialization of std::atomic before and after C++20

Consider the following two lines of code:

std::atomic_flag a { };                // Since C++20
std::atomic_flag a = ATOMIC_FLAG_INIT; // Until C++20

In C++20, the first line initializes a to the clear state, but if I use that in C++17, a will be initialized to an unspecified state. The second line is deprecated in C++20, but in C++ 17, it initializes a to the clear state. How can I have them both in a code? I guess I should use a macro, but what is that macro exactly? And does it work for the initialization of all the other std::atomic<T> types?

like image 375
Koosha Avatar asked Feb 02 '26 22:02

Koosha


1 Answers

atomic_flag is special. It is logically equivalent to an atomic<bool>, but the committee learned their lesson about having unique specializations with different behavior, so they made a completely separate type rather than a specialization of atomic for bools.

All atomic<T>s can be initialized by giving it a value of type T (so that's how you can get around the pre-C++20 value initialization nonsense). atomic_flag cannot be given a bool, since it doesn't store a bool. This is why it has that special ATOMIC_FLAG_INIT macro.

ATOMIC_FLAG_INIT may be deprecated, but it's not gone in C++20, so you are free to use it. In the relatively unlikely event that it gets removed for C++23, by then you should hopefully no longer have to support C++17.

like image 116
Nicol Bolas Avatar answered Feb 05 '26 12:02

Nicol Bolas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!