Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in-class initialization of atomic

Why in this example

struct Foo {
    atomic<int> x = 1;
};

the compiler (gcc 4.8) is trying to use the atomic& operator=(const atomic&) which is deleted, (hence the example wont compile), while here

struct Bar {
    Bar() { x = 1; }
    atomic<int> x;
};

it is calling the int operator=(int) as expected?

PS: I already know that

struct Xoo {
    atomic<int> x{1};
};

is fine (anyhow the better way to init x), but I am still curious about why Foo is broken.

PS: I misread the compiler error (and forgot to include it in the quesiton). It actually says:

 error: use of deleted function ‘std::atomic<int>::atomic(const std::atomic<int>&)’
   std::atomic<int> x = 1;
                        ^
 [...] error: declared here
       atomic(const atomic&) = delete;
       ^

so my above statement "...is trying to use the atomic& operator=(const atomic&) was just plain wrong.

like image 346
463035818_is_not_a_number Avatar asked May 12 '17 13:05

463035818_is_not_a_number


People also ask

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 does atomic do in C++?

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

std::atomic<int> x = 1; is copy-initialisation, and basically does this:

std::atomic<int> x{std::atomic<int>{1}};

Your compiler actually doesn't complain about operator=, but instead about the copy constructor.

(As you've pointed out, a later operator= call works just fine.)

Do a normal initialisation:

std::atomic<int> x{1};
like image 100
Lightness Races in Orbit Avatar answered Sep 28 '22 08:09

Lightness Races in Orbit