为什么在这个例子中
struct Foo {
atomic<int> x = 1;
};
编译器(gcc 4.8)正在尝试使用被删除的atomic& operator=(const atomic&)
(因此示例不会编译),而这里
struct Bar {
Bar() { x = 1; }
atomic<int> x;
};
按预期调用int operator=(int)
?
PS:我已经知道了
struct Xoo {
atomic<int> x{1};
};
很好(无论如何是初始化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;
^
所以我上面的陈述“......正在尝试使用atomic& operator=(const atomic&)
,这是完全错误的。
答案 0 :(得分:10)
std::atomic<int> x = 1;
是 copy-initialisation ,基本上是这样做的:
std::atomic<int> x{std::atomic<int>{1}};
您的编译器实际上并不抱怨operator=
,而是关于复制构造函数。
(正如您已经指出的那样,以后的operator=
通话工作正常。)
进行正常的初始化:
std::atomic<int> x{1};