I find that in practice, with a variety of C++11/C++14 compilers, a std::atomic
has an undefined initial value just as it would if it were a "raw" type. That is, we expect that for the expression
int a;
a
may have any value. It also turns out to be true that for the expression
std::atomic< int > b;
b
may also have any value. To say it another way,
std::atomic< int > b; // b is undefined
is not equivalent to
std::atomic< int > b{ 0 }; // b == 0
or to
std::atomic< int > b{}; // b == 0
because in the latter two cases b
is initialized to a known value.
My question is simple: where in the C++11 or C++14 spec is this behavior documented?
Each instantiation and full specialization of the std::atomic template defines an atomic type. Objects of atomic types are the only C++ objects that are free from data races; that is, if one thread writes to an atomic object while another thread reads from it, the behavior is well-defined.
However, you can use direct-initialization: std::atomic_bool World::mStopEvent(false); At your wish, you may choose to use braces instead of parentheses: std::atomic_bool World::mStopEvent{false};
Variables of type "int" have a default value of 0.
In order to solve this problem, C++ offers atomic variables that are thread-safe. The atomic type is implemented using mutex locks. If one thread acquires the mutex lock, then no other thread can acquire it until it is released by that particular thread.
[atomics.types.generic]/5 says this about integral specializations:
The atomic integral specializations and the specialization atomic shall have standard layout. They shall each have a trivial default constructor and a trivial destructor. They shall each support aggregate initialization syntax.
Moreover, the primary template synopsis at the beginning of the same section normatively specifies the default constructor as:
atomic() noexcept = default;
The effects are defined in [atomic.types.operations]/4 as:
Effects: leaves the atomic object in an uninitialized state.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With