微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/c/114974.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐