Why do global inline variables and static inline members in C++17 need guards?

Viewed 2039

Since C++17 it's possible to initialize global variables and static members in headers using the inline keyword. While I understand why static variables in functions need to be guarded (because initialization should happen only once even in a multithreaded context), I don't get why these new inline variables are also guarded (you can see it here: https://godbolt.org/z/YF8PeQ). I thought that in any case initialization of all globals and static members happens at the beginning of program execution (even before main()), so there's no need to think about multiple threads at this moment. Can you explain it, please?

1 Answers

Every file that contains the definition and uses it will try to initialize the variable. Even if that happens serially, not concurrently, you still need a way to mark the variable as initialized, so that only the first ocurrence will initialize it and later attempts to initialize it won't do anything.

Also, you can have multiple threads before main starts. Constructors of global variables (and functions called by those constructors) can spawn new threads.

So you can have multiple pieces of code, all executing before main, all trying to initialize the same variable. That's what the guards are for.

Related