definition from c++ reference: citation: https://en.cppreference.com/w/cpp/language/inline
inline variable is defined as inline static keyword. Hence
inline static vartype yourvariablename // is a inline variable.
Interesting note about inline "A function defined entirely inside a class/struct/union definition, whether it's a member function or a non-member friend function, is implicitly an inline function if it is attached to the global module"(C++ 20)
Ok from personal experience here's why inline static is a really really big thing:
If all you need todo is initialize a static variable in a C++ file then you can remove the C++ file and use inline static initialization(but your code will require C++ 17 and up)
Initializing static variables in pre C++ 17 classname templates is just overly verbose. You would have to do something like:
template
class classname
{
static yourtype yourstaticvariable = yourvalue; // and you'll have to initialize it
};
template yourtype classname::yourstaticvariable = yourvalue;
OR with inline static you can just do:
template <class T>
class classname
{
static yourtype yourstaticvariable = yourvalue; // initialized
}
- You can heavily exploit templates if you use inline static for initializing common things. Consider for instance the singleton where a inline static variable is perfect for tracking the instance and hence can be done in one file where before initializing the static variable would be painful. This becomes even more evident when you have multivariable templates.
- You need less C++ include files and less lib projects if you exploit inline static for single C++ header. This can heavily trim down files in a big project.
But there some caveats with inline static:
- You need C++ 17 and up
- You have to pay attention to issues of putting your initialization in a .h file(which you probably want to do if you initialize with inline static). Although this isn't necessarily a inline static issue but the decision to potentially moving everything to a header could lead to possible issues like namespace collisions, reusing macros or other things if you not careful with your order of inclusion.
But overall it's a fantastic feature. When in doubt initialize with inline static and break the I need a c++ file to initialize a static variable pattern.
static
has external linkage and "...It has the same address in every translation unit..." from en.cppreference.com/w/cpp/language/inline – Tonsureinline
may be defined in multiple translation units; So long as the definition is identical in every translation unit. It has external linkage. A variable declared as bothinline
andstatic
would have internal (or 'static') linkage. Exactly like with functions, except with dubious utility (global variables… 'Not dying on that hill). – Kappa