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?
In C++ 17 version, the inline variable concept has come. The inline variable is allowed to be defined in multiple translation units. It also follows the one definition rule. If this is defined more than one time, the compiler merges them all into a single object in final program.
That said, the function being static will not prevent it from being inlined; static functions are basically free functions with a different naming style and access to the class' private members.
A constexpr specifier used in a function or static data member (since C++17) declaration implies inline .
The Inline refactoring lets you reverse the Extract refactoring for a method , constructor, parameter, superclass, anonymous class, and variable. You can inline the pattern variable since the Java 14 version. In this case, all the occurrences will be replaced with old-style cast expression.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With