Let's consider a code
header:
class uid
{
public:
uid () {++i; }
static int i;
};
class foo
{
public:
const static uid id;
}
source:
static int uid::i = 0;
The header could be included into several source files, shared between compiler units and libraries.
Is it guaranteed that there would be only one instance off foo::id
, that foo::id::id()
would be called once at run-time and, the most important thing, would foo::id.i
be the same everywhere in the program and it's libraries? On the other hand another shared header could have bar
class with it's own static const uid id
which is expected to differ from foo
's one. Is it also guaranteed? If so, where actually foo::id
symbol is stored, especially in case of shared (dynamic-linked) libraries.
On some reason c++ disables
class foo
{
public:
const static int id = create_uid(); // forbidden
}
allowing only compile-time const initialisation or initialization in source file. So there was some reason to disable this kind of approach.