Some code I'm working with uses std::call_once so that some initialization only occurs once. However, there are global objects with constructors that can end up calling the initialization code.
In the following sample, call_once actually gets called twice. I guess it's because the once_flag constructor hasn't ran before it gets used. Is there a way around this so that some initialization code only gets called once without having to prohibit globals?
#include <mutex>
#include <iostream>
using namespace std;
void Init();
class Global
{
public:
Global()
{
Init();
}
};
Global global;
once_flag flag;
void Init()
{
call_once(flag, []{ cout << "hello" << endl; });
}
int main(int argc, char* argv[])
{
Init();
return 0;
}
Output is:
hello
hello