为什么原子不能与自动变量一起使用
why atomic does not work with auto varaible
我不确定以下语句有什么问题,它给了我编译错误。我们不能将"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
相关文章:
- 如何将两个字符串加在一起,就好像它们是变量一样?
- 为什么将三个变量与 == 一起比较会计算为 false?
- 在Visual Studio中,与std::async一起使用时不调用"thread_local"变量"析构函数,这是一个错误吗?
- 将cpp_redis pub/sub与条件变量一起使用时出现问题
- 字符串比较在与变量一起使用时给出不同的输出
- 为什么原子不能与自动变量一起使用
- 我可以将特征定义的变量与函数adjacent_difference一起使用吗?
- 为什么在 sizeof() 函数中与 * 运算符一起使用和不使用 * 运算符时,指向结构变量的指针大小会有所不同?
- 常量变量初始化仅与成员初始化列表一起工作
- 如何将数值变量与计时文字结合在一起
- 如何将初始值设定项与右值引用参数一起使用 // 为什么不能使用另一个 C 样式数组变量初始化 C 样式数组
- 与LLDB一起观看for循环中的变量i
- 将 std::sort 与指向整数变量的指针一起使用会产生意外的输出
- 有什么方法可以将字符串文字u8与变量一起使用吗
- 为什么类名与"::"一起使用在变量名之前?
- 当与可能导致缓冲区溢出的功能一起使用时,外部变量是否比其他变量更大
- 在C++中将cout与变量一起使用时出错
- 如何将结构变量与 scanf 一起使用
- 如何将结构与 *变量名称一起使用
- 我可以将 _T() 宏与变量一起使用吗?