I am a bit confused by the inline variable
introduced by C++17. What are the differences between inline variable
and inline static variable
? Also will this be affected by scope?
inline T var_no_scope;
inline static T static_var_no_scope;
namespace scope {
inline T var_scope;
inline static T static_var_scope;
}
Any explanation will be appreciated!
For me it becomes more interesting when it is a data members. In C++17
you can declare your static data members as inline
. The advantage is that you don't have to allocate space for them in a source file
. For example:
class A
{
// Omitted for brevity
static inline int b = 0;
};
So int A::b;
can be removed from the source file.
At namespace scope:
inline static
seems to be equivalent to just static
.
inline
on variables only has effect when you define the same variable in several translation units. Since static
restricts the variable to a single TU, you can't have more than one definition.
At class scope:
inline
can only appear on static
variables.
It has its normal effect, allowing you to initialize the variable directly in the header. Either:
struct A
{
inline static int a = 42;
};
Or:
struct A
{
static int a;
};
inline int A::a = 42;
At function scope:
inline
is not allowed.
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