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?
Seems not worth the effort to me for the most part. You’re really not improving readability, the unusual construct is going to confuse future programmers maintaining your code, and the addition of the new class increases complexity, thereby exposing you to the potential for more bugs.
I can see how you rarely might need or want to control the order of static initializations, or for some other reason wrap up all the statics. But from a readability point of view, I prefer the tried-and-true:
If you’ve got a lot of those statics, why not send them all off to their own CPP file? But then again, if you really have that many statics, I wonder if there’s something wrong with the overall design in the first place…