2016-09-26 55 views
0

當我試圖調用的std ::原子::店在初始化列表中,我得到了以下編譯器錯誤: g++ -std=c++11 test_function_call_in_ctor.cc的std ::原子::存儲不能在構造函數初始化列表稱爲

test_function_call_in_ctor.cc: In constructor ‘TestA::TestA()’: test_function_call_in_ctor.cc:7:17: error: expected ‘(’ before ‘.’ token TestA() : run_.store(true) { ^ test_function_call_in_ctor.cc:7:17: error: expected ‘{’ before ‘.’ token

如下

源代碼:

class TestA { 
    public: 
    TestA() : run_.store(true) { 
     cout << "TestA()"; 
     if (run_.load()) { 
     cout << "Run == TRUE" << endl; 
     } 
    } 
    ~TestA() {} 
    private: 
    std::atomic<bool> run_; 
}; 
int main() { 
    TestA a; 
    return 0; 
} 

在這個問題上的任何想法?非常感謝。

回答

2

初始化列表指定成員的構造函數的參數。正如你所嘗試的,你不能使用成員函數。然而,std::atomic<T>有一個構造採取T值arguemnt:

TestA(): run_(true) { ... } 

由於對象是正在建設它不可能被當時另一個線程使用,也就是說,沒有必要使用store()反正。

+0

謝謝,Dietmar。也許我沒有足夠清楚地描述我的問題。我嘗試的第一個版本正如你所提到的,然而,它在線程數據競爭檢查上失敗了,但是如果我把ctor中的run_.store(true),它會通過數據競爭檢查,並且發現初始化列表不能直接使用' :run_.store(true)'。我認爲你的回答是有道理的。 – Alan

0

因爲run_尚未構建。你應該調用在初始化列表中它的構造:

TestA() : run_(true) {} 
相關問題