我不确定以下语句有什么问题,它给了我编译错误。我们不能对原子变量使用“自动”吗?

#include <iostream>
#include<future>
#include <atomic>
using namespace std;

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

但是,如果我将“auto”替换为“int”,它将起作用。为什么?
int main()
{
  atomic<int> value(10);
  int NewValue = value;
}

编译错误与“自动”
 ||=== Build: Debug in Hello (compiler: GNU GCC Compiler) ===|
 F:\3d\C++CodeProject\Hello\main.cpp||In function 'int main()':|
 F:\3d\C++CodeProject\Hello\main.cpp|11|error: use of deleted function
 'std::atomic<int>::atomic(const std::atomic<int>&)'|
C:\Program Files
(x86)\CodeBlocks\MinGW\lib\gcc\mingw32\5.1.0\include\c++\atomic|612|note:
declared here|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 1 second(s)) ===|

最佳答案

auto与赋值右侧的数据类型匹配。在此语句中:

auto NewValue = value;
valuestd::atomic<int>,因此auto将推导为std::atomic<int>,而不是您期望的int

IOW,这个:
auto NewValue = value;

与此相同:
atomic<int> NewValue = value;

这是使用副本构造函数的copy initialization,但是std::atomic具有delete的d副本构造函数,这正是错误消息所说的内容:


std::atomic具有conversion operator for T ,这就是int NewValue = value;起作用的原因。

10-08 08:28
查看更多