How to ensure that std :: call_once is really only called once

Some of the code I'm working with uses std :: call_once, so some initialization happens only once. However, there are global objects with constructors that can eventually call the initialization code.

In the following example, call_once is actually called twice. I think this is because the once_flag constructor did not start before it will be used. Is there any way around this so that some kind of initialization code is called once without having to disable global variables?

#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:

hello
hello
+4
source share
1 answer

, once_flag constexpr (, . - http://en.cppreference.com/w/cpp/thread/once_flag). , /, "" ( ), " " - / POD. , - "", once_flag . MSVC, , ​​...

EDIT: , constexpr MSVC, ... , once_flag "" , - . , , , once_flag - http://www.parashift.com/c++-faq/static-init-order-on-first-use.html.

+4

All Articles