I recently read that Java now sports initialisation blocks like the following:
class C {
public C() { /* Instance Construction */ }
static { /* Static Initialisation */ }
{ /* Instance Initialisation */ }
}
I was particularly interested in the static
block. It got me thinking about the static initialisation order problem that affects many a novice C++ user, and typical workarounds for it, such as wrapping the static member in a free function, or using GNU's __attribute__((init_priority(n)))
extension.
I'm looking for some means of writing a method that will be called automatically to initialise the static members of a class, either when the first instance is created or simply at the start of the program, during ordinary static initialisation.
So far this is the best that's come to mind:
class C {
private:
class Static {
public:
Static();
int i;
Foo foo;
};
public:
static Static statics;
// ...
};
C::Static::Static() : i(42), foo("bar") {}
That is, wrap all of the static members in a class and create a static instance of that class, whose constructor serves as a static initialisation function. It's simple to alter this to instantiate the statics
member only when an instance is created, and even to ensure the proper destruction of static members.
The problem with this, of course, is that C::foo
becomes C::statics.foo
, which is rather unnatural. Is there a way to get around the awkward syntax, or is there a better solution altogether?