Is C++ static member variable initialization thread-safe?

It’s more a question of function-scoped static variables vs. every other kind of static variable, rather than scoped vs. globals.

All non-function-scope static variables are constructed before main(), while there is only one active thread. Function-scope static variables are constructed the first time their containing function is called. The standard is silent on the question of how function-level statics are constructed when the function is called on multiple threads. However, every implementation I’ve worked with uses a lock around the constructor (with a twice-checked flag) to guarantee thread-safety.

Leave a Comment