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.

+4


source to share


2 answers


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

      

+9


source


atomic<int> x = 1; // not an assignment.

      

is an

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

      



whereas

atomic<int> x;
x = 1; // assignment

      

+4


source







All Articles