Initialization in atomic class
Why in this example
struct Foo {
atomic<int> x = 1;
};
the compiler (gcc 4.8) tries to use atomic& operator=(const atomic&)
which is removed (from here the example will not compile), but here
struct Bar {
Bar() { x = 1; }
atomic<int> x;
};
does this cause int operator=(int)
as expected?
PS: I already know that
struct Xoo {
atomic<int> x{1};
};
this is fine (anyway the best way to initialize x
) but I'm still wondering why it Foo
works.
PS: I misread the compiler error (and forgot to include it in the question). This 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 "... trying to use atomic& operator=(const atomic&)
was simply not true.
source to share
std::atomic<int> x = 1;
is copy-initialized and basically does this:
std::atomic<int> x{std::atomic<int>{1}};
Your compiler doesn't actually complain about operator=
, but instead about the copy constructor.
(As you pointed out, the later call operator=
works just fine.)
Do some basic initialization:
std::atomic<int> x{1};
source to share