C++17 introduced inline variable, and an inline static data member can be defined in the class definition with an initializer. It does not need an out-of-class definition. For example,
struct X {
inline static int n = 1;
};
Given this, I see no reason not to always use inline static data members, for the neat syntax. Any pitfall of doing this? Note that I don't mind slower compilation.
Not a pitfall, but here's one reason not to use an
inline
: if the initial value of the variable is not just a trivial constant, but something more complicated:Now, the declaration of
figure_out_where_n_comes_from()
andand_then_more()
must be pulled into the header file, now.Also, whatever
figure_out_where_n_comes_from()
returns must also be declared. It could be some horribly overcomplicatedclass
, which then gets passed toand_then_more()
, as a parameter, to finally compute the initial value forn
.And everything that
#include
s the header file whereX
is declared must now include all the header files for all of these dependencies.But without an
inline
, all you have is:And you need to deal with all these dependencies only in one translation unit that instantiates
X::x
. Nothing else that#include
s onlyX
's header file cares about it.In other words: information hiding. If it's necessary to reimplement where the initial value of
n
comes from, you get to recompile only one translation unit, instead of your entire source code.