为什么在这个例子中
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&)
是完全错误的。
std::atomic<int> x = 1;
是复制初始化,基本上是这样做的:
std::atomic<int> x{std::atomic<int>{1}};
您的编译器实际上并不抱怨operator=
,而是关于复制构造函数。
(正如你所指出的,后来的operator=
通话效果很好。)
做正常的初始化:
std::atomic<int> x{1};
atomic<int> x = 1; // not an assignment.
是
atomic<int> x{atomic<int>{1}};
而
atomic<int> x;
x = 1; // assignment