When I was trying to call std::atomic::store in initialization list, I got following compiler error: 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
source code as below:
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;
}
Any idea on this issue? Thanks a lot.
The initializer list specifies the constructor arguments of the members. You cannot use a member function as you tried. However, std::atomic<T>
has a constructor taking a T
value as arguemnt:
TestA(): run_(true) { ... }
Since the object is under construction it can't possibly be used by another thread at that time, ie, there is no need to use store()
anyway.
Because run_
hasn't been constructed. You should call its constructor in the initializer list:
TestA() : run_(true) {}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.