c – 原子的类内初始化
发布时间:2020-12-16 10:37:24 所属栏目:百科 来源:网络整理
导读:为什么在这个例子中 struct Foo { atomicint x = 1;}; 编译器(gcc 4.8)正在尝试使用原子和放大器. operator =(const atomic)被删除,(因此示例不会编译),而这里 struct Bar { Bar() { x = 1; } atomicint x;}; 它按预期调用int运算符=(int)? PS:我已经知道
为什么在这个例子中
struct Foo { atomic<int> x = 1; }; 编译器(gcc 4.8)正在尝试使用原子和放大器. operator =(const atomic&)被删除,(因此示例不会编译),而这里 struct Bar { Bar() { x = 1; } atomic<int> x; }; 它按预期调用int运算符=(int)? PS:我已经知道了 struct Xoo { atomic<int> x{1}; }; 很好(无论如何是init x的更好方法),但我仍然很好奇为什么Foo被打破了. PS:我误读了编译器错误(并且忘了将它包含在问题中).它实际上说: error: use of deleted function ‘std::atomic<int>::atomic(const std::atomic<int>&)’ std::atomic<int> x = 1; ^ [...] error: declared here atomic(const atomic&) = delete; ^ 所以我上面的陈述“……试图使用原子& operator =(const atomic&)是完全错误的. 解决方法
的std ::原子< INT> x = 1;是复制初始化,基本上是这样的:
std::atomic<int> x{std::atomic<int>{1}}; 你的编译器实际上不会抱怨operator =,而是关于复制构造函数. (正如你所指出的,后来的operator = call工作正常.) 做正常的初始化: std::atomic<int> x{1}; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |