c – “使用已删除的函数”错误与std :: atomic_int

我想使用一个std :: atomic_int变量.在我的代码中,我有
#include <atomic>

std::atomic_int stop = 0;

int main()
{
    // Do something
}

这给我一个编译错误

use of deleted function 'std::__atomic_base<_IntTp>::__atomic_base(const std::__atomic_base<_IntTp>&) [with _ITp = int]'
 std::atomic_int stop = 0;
                        ^

关于发生什么的任何想法?

解决方法

您的代码正在尝试在RHS上构造临时std :: atomic_int,然后使用std :: atomic_int复制构造函数(被删除)来初始化停止,如下所示:
std::atomic_int stop = std::atomic_int(0);

这是因为,在这里执行的复制初始化并不完全等同于其他类型的初始化.

[C++11: 8.5/16]: The semantics of initializers are as follows [..]

If the initializer is a (non-parenthesized) braced-init-list,the object or reference is list-initialized (8.5.4).

(这个答案允许选项3)

[..]

If the destination type is a (possibly cv-qualified) class type:

  • If the initialization is direct-initialization,or if it is copy-initialization where the cv-unqualified version of the source type is the same class as,or a derived class of,the class of the destination,constructors are considered. The applicable constructors are enumerated (13.3.1.3),and the best one is chosen through overload resolution (13.3). The constructor so selected is called to initialize the object,with the initializer expression or expression-list as its argument(s). If no constructor applies,or the overload resolution is ambiguous,the initialization is ill-formed.

(这几乎描述了你的代码,但不完全相同;这里的关键是,也许与直觉相反,std :: atomic_int的构造函数在你的情况下根本不被考虑!)

  • Otherwise (i.e.,for the remaining copy-initialization cases),user-defined conversion sequences that can convert from the source type to the destination type or (when a conversion function is used) to a derived class thereof are enumerated as described in 13.3.1.4,and the best one is chosen through overload resolution (13.3). If the conversion cannot be done or is ambiguous,the initialization is ill-formed. The function selected is called with the initializer expression as its argument; if the function is a constructor,the call initializes a temporary of the cv-unqualified version of the destination type. The temporary is a prvalue. The result of the call (which is the temporary for the constructor case) is then used to direct-initialize,according to the rules above,the object that is the destination of the copy-initialization. In certain cases,an implementation is permitted to eliminate the copying inherent in this direct-initialization by constructing the intermediate result directly into the object being initialized; see 12.2,12.8.

(这是你的场景,所以尽管复制可以被删除,但仍然有可能)

  • [..]

无论如何,这是修复;使用直接初始化或列表初始化:

std::atomic_int stop(0);     // option 1
std::atomic_int stop{0};     // option 2
std::atomic_int stop = {0};  // option 3

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...