Is the following code thread-safe? (Using a IIFE to initialize a static local variable.)
int MyFunc(){
static int Val = ([]()
{
return 1 + 2 + 3 + 4; // Real code is more complex, but thread-safe
})();
return Val;
}
Is the following code thread-safe? (Using a IIFE to initialize a static local variable.)
int MyFunc(){
static int Val = ([]()
{
return 1 + 2 + 3 + 4; // Real code is more complex, but thread-safe
})();
return Val;
}
Yes. C++11 (and above) guarantees no data races between multiple threads trying to initialize a static local variable. If the code inside your lambda is thread-safe, the initialization will be as well.
Using a lambda, function call, or constructor doesn't change the thread-safety of the initialization.