c++ - In-class initialization of static data members -
in c++, static
members may not initialized in class body these exceptions:
static
members ofconst
integral type can bestatic
members ofconstexpr
literal type must be
can explain why these exceptions?
also, holds:
even if
const static
data member initialized in class body, member ordinarily should defined outside class definition.
this never understood @ all. what's point of definition?
just trying intuitions here.
why can there initializer in class definition?
concerning 2 exceptions const
, constexpr
static data members:
[class.static.data]/3
[ note: in both these cases, member may appear in constant expressions. — end note ]
i.e. initializer, may use them in constant expressions, e.g.
struct s { static std::size_t const len = 10; int arr[len]; }; std::size_t const s::len;
if len
wasn't initialized in class definition, compiler couldn't know value in next line define length of arr
.
one argue allowing initializers of non-const
, non-constexpr
static data members in class definition, interfere initialization order:
[basic.start.init]/2
definitions of explicitly specialized class template static data members have ordered initialization. other class template static data members (i.e., implicitly or explicitly instantiated specializations) have unordered initialization. other non-local variables static storage duration have ordered initialization.
that is, order of definitions including initializers important. order of (dynamic) initialization of non-local objects defined within translation unit, reason why there has definition including initializer non-const
, non-constexpr
static data members.
what's point of definition?
this has been answered in comments imo. might want add odr, is, name external linkage, static data member must (only) defined in 1 translation unit (if it's odr-used). it's programmer choose translation unit.
Comments
Post a Comment