C++ 初始化静态原子成员变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20453054/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Initialize static atomic member variable
提问by Teisman
I would like to generate identifiers for a class named orderin 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!
我想以线程安全的方式为名为order的类生成标识符。下面的代码不能编译。我知道原子类型没有复制构造函数,我认为这解释了为什么这段代码不起作用。有没有人知道让这段代码真正起作用的方法?我还在学习,所以如果我走错了路,也请告诉我(如果是这样,如果你能指出我的替代方法,我将不胜感激)。谢谢!
#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
回答by Mike Seymour
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.
无论如何,您可能更喜欢这样做,除非您喜欢阅读不必要的冗长代码。
回答by Some programmer dude
How about the definition
怎么定义
std::atomic<int> order::c{0}
回答by anhldbk
Also you can use atomic_init
:
你也可以使用atomic_init
:
std::atomic<int> data;
std::atomic_init(&data, 0);