Initialize once_flag?

What is once_flag to be initialized? I tried false and 0 , and both set errors like the ones below (below 0 ):

 no viable conversion from 'int' to 'std::once_flag' 

This is how I try to use it. (I believe that bad style does not initialize static, even if the language initializes them, so I would prefer something there).

 MyClass& GetMyClass() { static std::once_flag flag; static MyClass cls; std::call_once(flag, []() { // Initialize class }); return cls; } 
+6
source share
4 answers

Update

If we look at the draft standard section of C ++ 30.4.4.1 Struct once_flag, we can see that the constructor is defined as:

 constexpr once_flag() noexcept; 

since it is constexpr, your static instance will be statically initialized, and we can see an example in section 30.4.4.2 function, which uses a static instance:

 void g() { static std::once_flag flag2; std::call_once(flag2, initializer()); } 

Original

If we look at the documentation on std :: once_flag , it says:

 once_flag(); Cnstructs an once_flag object. The internal state is set to indicate that no function has been called yet. 

and if we look further at the documentation of the call_once document, we will see the following example demonstrating how to use std::once_flag :

 #include <iostream> #include <thread> #include <mutex> std::once_flag flag; void do_once() { std::call_once(flag, [](){ std::cout << "Called once" << std::endl; }); } int main() { std::thread t1(do_once); std::thread t2(do_once); std::thread t3(do_once); std::thread t4(do_once); t1.join(); t2.join(); t3.join(); t4.join(); } 

with the following expected output:

 Called once 
+5
source

Since your question was answered elsewhere, as an alternative to the code you sent, you can also do this:

 // private function in anonymous namespace or something MyClass& initMyClass() { static MyClass c; /* initialize c */ return c; } 

and then the client calls

 MyClass& GetMyClass() { static MyClass& c = initMyClass(); return c; } 

because static initializations are now thread safe in C ++ 11. And then you don’t have to bother with call_once or anything else.

+2
source

what are you trying to do? you cannot initialize std::once_flag any value since it has only one constructor that takes no arguments.

http://en.cppreference.com/w/cpp/thread/once_flag

once_flag (); Creates a once_flag object. An internal state is set to indicate that the function has not yet been called.

By the way, why do you think that not initializing a static variable is a bad style?

+1
source

ONCE_FLAG_INIT

EDIT: only C, not C ++. Defined by <threads.h> .

+1
source

Source: https://habr.com/ru/post/958120/


All Articles