Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++17 inline variable vs inline static variable

Tags:

c++

c++17

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!

like image 474
Jes Avatar asked May 24 '18 18:05

Jes


2 Answers

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.

like image 103
Ja_cpp Avatar answered Oct 03 '22 00:10

Ja_cpp


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.

like image 45
HolyBlackCat Avatar answered Oct 03 '22 01:10

HolyBlackCat