当我试图在初始化列表中调用std :: atomic :: store时,我遇到了以下编译器错误:
g++ -std=c++11 test_function_call_in_ctor.cc
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;
}
关于这个问题的任何想法?非常感谢。
答案 0 :(得分:2)
初始化列表指定成员的构造函数参数。您不能尝试使用成员函数。但是,std::atomic<T>
有一个构造函数将T
值作为arguemnt:
TestA(): run_(true) { ... }
由于对象正在构建中,因此当时不可能被另一个线程使用,即无论如何都不需要使用store()
。
答案 1 :(得分:0)
因为尚未构建run_
。您应该在初始化列表中调用其构造函数:
TestA() : run_(true) {}