简体   繁体   English

初始化静态原子成员变量

[英]Initialize static atomic member variable

I would like to generate identifiers for a class named order in a threadsafe manner. 我想以线程安全的方式为名为order的类生成标识符。 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

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. 无论如何,你应该更喜欢它,除非你喜欢阅读不必要的详细代码。

怎么定义

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

Also you can use atomic_init : 你也可以使用atomic_init

std::atomic<int> data;
std::atomic_init(&data, 0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM