[英]error C2280: attempting to reference a deleted function (atomic<int>)
I have a class A
with a member variable _atomicVar
of type std::atomic<int>
. 我有一个
class A
,其成员变量_atomicVar
类型为std::atomic<int>
。
#include <atomic>
class A
{
public:
A();
~A();
private:
std::atomic<int> _atomicVar;
};
If I build the project I get the following error: 如果我构建项目,我会收到以下错误:
error C2280: 'std::atomic<int>::atomic(const std::atomic<int> &)' : attempting to reference a deleted function
I'm mainly a C# developer so I don't know every detail of C++ (yet). 我主要是一个C#开发人员,所以我还不知道C ++的每一个细节。 I don't know where I use the copy c'tor of
atomic<int>
. 我不知道我在哪里使用
atomic<int>
的copy c'tor。
I also tried to initialize _atomicVar
: 我还尝试初始化
_atomicVar
:
std::atomic<int> _atomicVar { 0 };
... but that didn't work. ......但那没用。
I would expect that _atomicVar
(without an explicit initialization) would get initialized with the default value for int
. 我希望
_atomicVar
(没有显式初始化)将使用int
的默认值进行初始化。
Can you tell me why this error occurs? 你能告诉我为什么会出现这个错误吗?
That's because copy constructor of std::atomic
is deleted . 那是因为删除了
std::atomic
拷贝构造函数。
See this documentation page . 请参阅此文档页面 。
Since you do not define explicit copy constructor for A
, compiler generates default one, which simply calls copy constructors for all members (which is not allowed for std::atomic
). 由于您没有为
A
定义显式复制构造函数,因此编译器会生成默认复制构造函数,它只调用所有成员的复制构造函数( std::atomic
不允许这样做)。
Solution: 解:
class A
{
public:
A();
A(const A& origin); // add this line
~A();
private:
std::atomic<int> _atomicVar;
};
A::A(const A& origin)
: _atomicVar(0) //zero-initialize _atomicVar
{
}
EDIT 编辑
If you wonder, why atomic
types are not copyable, you may want to read this question , especially accepted answer. 如果你想知道为什么
atomic
类型不可复制,你可能想要阅读这个问题 ,特别是接受的答案。 If you want to copy value of std::atomic
, you can do it: 如果要复制
std::atomic
值,可以这样做:
A::A(const A& origin)
: _atomicVar(origin._atomicVar.load())
{
}
But keep in mind, that this operation itself will not be an atomic one (and, for most logics, meaningless). 但请记住,这个操作本身不会是原子操作(并且对于大多数逻辑来说,没有意义)。
Also, you may also want to define explicit assignment operator (remember about Rule of Three ). 此外,您可能还需要定义显式赋值运算符(请记住关于三元规则 )。
The best option for proper behaviour of your program would be deleting these two methods: 正确执行程序的最佳选择是删除以下两种方法:
class A
{
public:
A();
A(const A&) = delete;
~A();
A& operator=(const A&) = delete;
private:
std::atomic<int> _atomicVar;
};
If your compiler doesn't support this (eg any VC before VC12), declare them as private and do not provide a body: 如果您的编译器不支持此功能(例如VC12之前的任何VC),请将它们声明为私有,并且不提供正文:
class A
{
public:
A();
~A();
private:
//do not define these two
A(const A&);
A& operator=(const A&);
private:
std::atomic<int> _atomicVar;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.