Scott Meyers writes in Effective Modern C++ (Item 30, at page 210) that there's
no need to define integral
static const
data members in classes; declarations alone suffice,
then the sample code is
class Widget {
public:
static const std::size_t MinVals = 28; // MinVals' declaration;
...
};
... // no defn. for MinVals
std::vector<int> widgetData;
widgetData.reserve(Widget::MinVals); // use of MinVals
I was convinced that static const std::size_t MinVals = 28;
is declaration and also a definition, as it is giving a value to MinVals
, but the comment seems to claim that's only a declaration; the second comment actually claims there's no definition. The text after the code, indeed reads
MinVals
lacks a definition.
Which confirms that static const std::size_t MinVals = 28;
is not a definition, so I'm a bit confused.
cppreference doesn't help me much (my bold-italic):
If a
static
data member of integral or enumeration type is declaredconst
(and notvolatile
), it can be initialized with an initializer in which every expression is a constant expression, right inside the class definition:struct X { const static int n = 1; const static int m{2}; // since C++11 const static int k; }; const int X::k = 3;
but first two lines in the class look definitions to me.
The same goes for a following example on cppreference:
struct X { static const int n = 1; static constexpr int m = 4; }; const int *p = &X::n, *q = &X::m; // X::n and X::m are odr-used const int X::n; // … so a definition is necessary constexpr int X::m; // … (except for X::m in C++17)
where I'd have said static const int n = 1;
is a definition, but it is not, based on the second to last comment.
The declaration of a non-inline static data member in its class definition is not a definition [...]
. But (3) is directly for integral types with an initializer and this paragraph does not help if this is a declaration or definition. – Anninline static
, and it's awesome. – Neutrophil