I understand that the C "magic static" pattern guarantees thread-safe initialization of a local variable, since C 11. Does this hold true no matter how the local is initialized?
int some_expensive_func();
void test()
{
static int attempt1{some_expensive_func()};
static int attempt2 = {some_expensive_func()};
static int attempt3 = some_expensive_func();
static int attempt4(some_expensive_func());
}
I have an in-house static-analysis checker that's complaining about the thread-safety of the third style shown above, but I think it's OK, and I'm looking for confirmation. Thanks.
CodePudding user response:
Yes, all initialization styles are thread-safe for local static variables (since C 11). The only thing that wouldn't be thread-safe is something that's not actually an initialization, e.g., something like this:
static int x; // zero-initialized on program startup
x = some_expensive_func(); // this is assignment, not initialization