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