2017-05-12 106 views
3

初始化正在尝试使用该被删除atomic& operator=(const atomic&),(因此例如不会编译),而在这里在级在本实施例中</p> <pre><code>struct Foo { atomic<int> x = 1; }; </code></pre> <p>的编译器(gcc 4.8)为什么的原子

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

使用'at omic x {1};'。 – Jarod42

+0

@ Jarod42是的,我已经意识到这个工作,但仍然好奇为什么'Foo'坏了 – user463035818

+0

它与成员初始化顺便说一句,在正常范围内,你会有同样的问题。 – Jarod42

回答

9

std::atomic<int> x = 1;复制初始化,基本上做到这一点:

std::atomic<int> x{std::atomic<int>{1}}; 

您的编译器实际上不会抱怨operator=,而是关于复制构造函数。

(正如您所指出的那样,以后operator=调用工作就好了。)

做一个正常的初始化:

std::atomic<int> x{1}; 
+0

我实际上会投票关闭quesiton,因为“误读了编译器的错误信息”,但是因为已经有答案了,所以我想我可以只接受一个,并将其作为下次付出更多注意力的教训;) – user463035818

+0

@ tobi303:fbm :P –

3
atomic<int> x = 1; // not an assignment. 

atomic<int> x{atomic<int>{1}}; 

atomic<int> x; 
x = 1; // assignment 
相关问题