对于具有std :: atomic成员变量的类的复制构造函数/赋值运算符出错 [英] Error with copy constructor/assignment operator for a class which has std::atomic member variable

查看:4501
本文介绍了对于具有std :: atomic成员变量的类的复制构造函数/赋值运算符出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类如下。

#include <atomic>

static const long  myValue = 0;

class Sequence
{

public:

    Sequence(long initial_value = myValue) : value_(initial_value) {}


private:

     std::atomic<long> value_;
};

int main()
{
         Sequence firstSequence;
         Sequence secondSequence = firstSequence;
         return 0;
}

我收到这样的编译错误,

I am getting compilation error like this,

test.cpp:21:36: error: use of deleted function ‘Sequence::Sequence(const Sequence&)’
test.cpp:5:7: error: ‘Sequence::Sequence(const Sequence&)’ is implicitly deleted because the default definition would be ill-formed:
test.cpp:5:7: error: use of deleted function ‘std::atomic<long int>::atomic(const std::atomic<long int>&)’

这是默认的复制构造函数和赋值操作符在这种情况下不工作?

Is that the default copy constructor and assignment opertaor do not work in such case?

PS:我使用gcc版本4.6.3

PS: I am using gcc version 4.6.3

推荐答案

不能使用标准复制构造函数复制原子,因为所有加载和存储必须明确发生。你必须为 Sequence 编写自己的拷贝构造函数,它会对 value_(rhs.value_.load())进行一些初始化。 code>(可能有更宽松的内存排序)。

You can't copy atomics with a standard copy constructor, since all loads and stores must happen explicitly. You'll have to write your own copy constructor for Sequence which does some initialization of the form value_(rhs.value_.load()) (possibly with more relaxed memory ordering).

这篇关于对于具有std :: atomic成员变量的类的复制构造函数/赋值运算符出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆