c++atomicin-class-initialization

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.


Solution

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