Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 955
John Lettehw Avatar asked Jun 27 '19 21:06

John Lettehw


People also ask

What is inline variable in C++?

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.

Can static member function inline?

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.

Is Constexpr inline?

A constexpr specifier used in a function or static data member (since C++17) declaration implies inline .

What is inline variable in Java?

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.


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.

like image 73
Jonathan Wakely Avatar answered Sep 29 '22 08:09

Jonathan Wakely