c++ - How to ensure std::call_once really is only called once -
some code i'm working uses std::call_once initialization occurs once. however, there global objects constructors can end calling initialization code.
in following sample, call_once gets called twice. guess it's because once_flag constructor hasn't ran before gets used. there way around initialization code gets called once without having 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
according specs, once_flag
should have trivial constexpr
constructor (for example see here - http://en.cppreference.com/w/cpp/thread/once_flag ). in place, if global/static, not "constructed" (no actual function executed), more "value initialized" - global/static pod type. in case not possible have constructor run "before" once_flag
initialized. given comment using msvc, guess can bug in implementation...
edit: according comment below, constexpr
not supported on msvc @ all, options limited in here... if have in 1 file, put once_flag
"above" uses - constructors in file executed in order of declaration of objects. if have users spread across different files, option use function provides access static internal once_flag
- in answer http://www.parashift.com/c++-faq/static-init-order-on-first-use.html .
Comments
Post a Comment