为什么原子不能与自动变量一起使用

why atomic does not work with auto varaible

本文关键字:变量 一起 不能 为什么      更新时间:2023-10-16

我不确定以下语句有什么问题,它给了我编译错误。我们不能将"auto"与原子变量一起使用吗?

#include <iostream>
#include<future>
#include <atomic>
using namespace std;
int main()
{
atomic<int> value(10);
auto   NewValue = value;
}

但是如果我用"int"替换"auto",它可以工作。为什么?

int main()
{
atomic<int> value(10);
int NewValue = value;
}

"自动"编译错误

||=== Build: Debug in Hello (compiler: GNU GCC Compiler) ===|
F:3dC++CodeProjectHellomain.cpp||In function 'int main()':|
F:3dC++CodeProjectHellomain.cpp|11|error: use of deleted function 
'std::atomic<int>::atomic(const std::atomic<int>&)'|
C:Program Files 
(x86)CodeBlocksMinGWlibgccmingw325.1.0includec++atomic|612|note: 
declared here|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 1 second(s)) ===|

auto匹配赋值右侧的数据类型。 在此声明中:

auto NewValue = value;

value是一个std::atomic<int>,所以auto会推断出std::atomic<int>,而不是像你期望的那样int

IOW,这个:

auto NewValue = value;

与此相同:

atomic<int> NewValue = value;

这是使用复制构造函数进行复制初始化,但std::atomic有一个delete复制构造函数,这正是错误消息所说的:

使用已删除的函数 'std::atomic::atomic(const std::atomic&('

std::atomic有一个用于T的转换运算符,这就是int NewValue = value;工作的原因。

原子变量不可复制构造: http://en.cppreference.com/w/cpp/atomic/atomic/atomic (3(

这是auto在这种情况下将尝试执行的操作。

但是,您可以将其转换为int,使用operator int转换:http://en.cppreference.com/w/cpp/atomic/atomic/operator_T