Initialize static atomic member variable

44,931

Solution 1

I know that the atomic types do not have copy constructors, and I assume that explains why this code does not work.

Yes, the error says that quite clearly.

Does anybody know a way to actually get this code to work?

Instead of copy-initialising from a temporary, which requires an accessible copy constructor:

std::atomic<int> order::c = std::atomic<int>(0);

use direct-initialisation, which doesn't:

std::atomic<int> order::c(0);   // or {0} for a more C++11 experience

You should probably prefer that anyway, unless you enjoy reading unnecessarily verbose code.

Solution 2

How about the definition

std::atomic<int> order::c{0}

Solution 3

Also you can use atomic_init:

std::atomic<int> data;
std::atomic_init(&data, 0);
Share:
44,931
Teisman
Author by

Teisman

Developer at http://www.gigstarter.nl

Updated on June 02, 2020

Comments

  • Teisman
    Teisman almost 4 years

    I would like to generate identifiers for a class named order in a threadsafe manner. The code below does not compile. I know that the atomic types do not have copy constructors, and I assume that explains why this code does not work. Does anybody know a way to actually get this code to work? I'm still learning, so please also let me know if I'm on the wrong track (if so, I would appreciate it if you could point me to an alternative approach). Thanks!

    #include <atomic>
    #include <iostream>
    
    class order {
    public: 
        order() { id=c.fetch_add(1); }
        int id;
    private:
        static std::atomic<int> c;
    };
    
    std::atomic<int> order::c = std::atomic<int>(0);
    
    int main() {
        order *o1 = new order();
        order *o2 = new order();
        std::cout << o1->id << std::endl; // Expect 0
        std::cout << o2->id << std::endl; // Expect 1
    }
    

    Compiling the above results in the following error:

    order.cpp:45:51: error: use of deleted function 
            ‘std::atomic<int>::atomic(const std::atomic<int>&)’
    In file included from order.cpp:3:0:
    /usr/include/c++/4.7/atomic:594:7: error: declared here
    
  • Teisman
    Teisman over 10 years
    Thanks a lot Joachim! I've upvoted your answer but I'll accept Mike's as it is a bit more verbose. Hope you don't mind! ;)
  • Sergei Krivonos
    Sergei Krivonos over 5 years
    this would not be initialized during compilation?
  • anicicn
    anicicn almost 5 years
    Isn't static variable thread safe from c++11? I see the ++11 tag up in the question. So why do we need atomics on the first place? Why can't we just use regular int?