簡體   English   中英

原子的類內初始化

[英]in-class initialization of atomic

為什么在這個例子中

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};
};

很好(無論如何是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;
       ^

所以我上面的陳述“......試圖使用atomic& operator=(const atomic&)是完全錯誤的。

std::atomic<int> x = 1; 復制初始化 ,基本上是這樣的:

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

你的編譯器實際上不會抱怨operator= ,而是關於復制構造函數。

(正如你所指出的,后來的operator= call工作正常。)

做正常的初始化:

std::atomic<int> x{1};
atomic<int> x = 1; // not an assignment.

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

atomic<int> x;
x = 1; // assignment

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM