Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the default value for a std::atomic?

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?

like image 804
OldPeculier Avatar asked Mar 30 '16 21:03

OldPeculier


People also ask

What is std :: atomic in C++?

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.

How do you initialize atomic bool?

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};

What is the default value of INT in C++?

Variables of type "int" have a default value of 0.

How do you declare an atomic variable in C++?

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.


1 Answers

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

like image 93
Kerrek SB Avatar answered Sep 28 '22 22:09

Kerrek SB