1

When class B is used as a static local variable in class A constructor, does c++11 will make sure func() be initialized only once in a thread-safe manner? Are the codes commented out redundant?

void func() {}

class B {
  B() {
    //static std::atomic<char> first_call(1);
    //if (first_call.fetch_and((char)0)) {
      func();
    //} 
  }
};

class A {
  A(){
    static B;
  }
};
Yulong Ao
  • 1,199
  • 1
  • 14
  • 22
  • if you want to be more explicit, there is also [`std::call_once`](https://en.cppreference.com/w/cpp/thread/call_once) – kmdreko Nov 06 '18 at 03:16
  • Also see [Is returning local static object thread safe for pre-c++11 compilers](https://stackoverflow.com/q/27286444/1708801) – Shafik Yaghmour Nov 06 '18 at 03:16
  • [this](https://en.cppreference.com/w/cpp/language/storage_duration#Static_local_variables) explains it in detail. – Praveen Nov 06 '18 at 03:27

0 Answers0