Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the difference between std::call_once and function-level static initialization

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 );
}
like image 365
pal Avatar asked Jul 01 '13 14:07

pal


People also ask

What is std :: Call_once?

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.

Can we initialize static variable in function?

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.

Is std :: Call_once thread safe?

The CPP Reference states std::call_once is thread safe: Executes the function f exactly once, even if called from several threads.

At what point during a program's execution are automatic external static variables initialized?

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)


1 Answers

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.

like image 83
Jonathan Wakely Avatar answered Sep 19 '22 01:09

Jonathan Wakely