I would like to generate identifiers for a class named order
in a thread-safe 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? Is there an alternative approach?
#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