错误 C2280:试图引用已删除的函数 (atomic<int>)

error C2280: attempting to reference a deleted function (atomic<int>)

我有一个 class A,其成员变量 _atomicVar 类型为 std::atomic<int>

#include <atomic>

class A
{
public:
    A();
    ~A();

private:
    std::atomic<int> _atomicVar;
};

如果我构建项目,我会收到以下错误:

error C2280: 'std::atomic<int>::atomic(const std::atomic<int> &)' : attempting to reference a deleted function

我主要是一名 C# 开发人员,所以我还不了解 C++ 的每个细节(还)。我不知道我在哪里使用 atomic<int>.
的复制函数 我也尝试初始化 _atomicVar:

std::atomic<int> _atomicVar { 0 };

...但这没有用。
我希望 _atomicVar (没有显式初始化)将使用 int.
的默认值进行初始化 你能告诉我为什么会出现这个错误吗?

那是因为std::atomic的复制构造函数被删除了

this documentation page

由于您没有为 A 定义显式复制构造函数,编译器生成默认复制构造函数,它只为所有成员调用复制构造函数(std::atomic 不允许)。

解决方案:

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
{
}

编辑

如果您想知道为什么 atomic 类型不可复制,您可能需要阅读 this question,尤其是已接受的答案。如果你想复制std::atomic的值,你可以这样做:

A::A(const A& origin)
: _atomicVar(origin._atomicVar.load())
{
}

但请记住,此操作本身不会是原子操作(并且对于大多数逻辑而言,它是无意义的)。

此外,您可能还想定义显式赋值运算符(记住 Rule of Three)。

使程序正常运行的最佳选择是删除这两个方法:

class A
{
public:
    A();
    A(const A&) = delete;
    ~A();

    A& operator=(const A&) = delete;

private:
    std::atomic<int> _atomicVar;
};

如果您的编译器不支持此功能(例如 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;
};