具有 std::atomic 成员变量的类的复制构造函数/赋值运算符出错 [英] Error with copy constructor/assignment operator for a class which has std::atomic member variable
本文介绍了具有 std::atomic 成员变量的类的复制构造函数/赋值运算符出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个如下所示的课程.
I have a class like below.
#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())
形式进行一些初始化(可能具有更宽松的内存排序)).
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屋!
查看全文