1) std::call_once
A a;
std::once_flag once;
void f ( ) {
call_once ( once, [ ] { a = A {....}; } );
}
2) function-level static
A a;
void f ( ) {
static bool b = ( [ ] { a = A {....}; } ( ), true );
}
std::call_once ensures execution of a function exactly once by competing threads. It throws std::system_error in case it cannot complete its task.
Static functions can be called directly by using class name. Static variables are initialized only once. Compiler persist the variable till the end of the program. Static variable can be defined inside or outside the function.
The CPP Reference states std::call_once is thread safe: Executes the function f exactly once, even if called from several threads.
static variables are only initialized once when the program is first loaded into memory (not each time that the function is called like automatic or local variables)
For your example usage, hmjd's answer fully explains that there is no difference (except for the additional global once_flag
object needed in the call_once
case.) However, the call_once
case is more flexible, since the once_flag
object isn't tied to a single scope. As an example, it could be a class member and be used by more than one function:
class X {
std::once_flag once;
void doSomething() {
std::call_once(once, []{ /* init ...*/ });
// ...
}
void doSomethingElse() {
std::call_once(once, []{ /*alternative init ...*/ });
// ...
}
};
Now depending on which member function is called first the initialization code can be different (but the object will still only be initialized once.)
So for simple cases a local static works nicely (if supported by your compiler) but there are some less common uses that might be easier to implement with call_once
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With