0

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.

  • provide a link to magic static. and i don't see in your code how anything gets called. – Neil Butterworth Jan 11 '23 at 20:30
  • 6
    Any of this expression is "initialization", just slightly different form of initialization. And since initialization is guranteed to be thread-safe it didn't matter which form it have. – sklott Jan 11 '23 at 21:03
  • @NeilButterworth I linked to a relevant SO post about magic statics. The term isn't explicitly used in the linked answer, but it is elsewhere in the post, and it's seen elsewhere on the web. I'm not sure what you mean about "how anything gets called" though. – Peter Yurkosky Jan 11 '23 at 21:37
  • Function-local static object initialization is required to be thread-safe. Don't know what the "magic" part is about. – Pete Becker Jan 11 '23 at 21:47
  • @PeteBecker I've seen this "magic static" phrase in a number of places, usually in reference to the way this feature can be used to implement singletons (see http://www.nuonsoft.com/blog/2017/08/10/implementing-a-thread-safe-singleton-with-c11-using-magic-statics/). – Peter Yurkosky Jan 12 '23 at 00:49

1 Answers1

2

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
Brian Bi
  • 111,498
  • 10
  • 176
  • 312
  • Thanks for the answer, that's pretty clear. In the comment, do you mean "zero-initialized on first access"? I thought we were discussing static _locals_, not globals. Or does something about the initialization change when the local is not initialized? – Peter Yurkosky Jan 12 '23 at 01:11
  • @PeterYurkosky Zero-initialization and constant initialization occur during program startup, even for local static variables. For local statics, any remaining initialization that needs to be performed is performed when control passes through the definition for the first time. – Brian Bi Jan 12 '23 at 01:31