Boost logo

Boost :

Subject: Re: [boost] Is there any interest in static constructors?
From: Alexander Stoyan (alexander.stoyan_at_[hidden])
Date: 2013-02-01 12:09:41

Hello Mathias,

I'm afraid you didn't get the point. Let me explain.

>> The object will only be constructed when instance() is called

Technically, yes, the instance will be create once singleton::instance is
called for the first time, but in order to make it constructed BEFORE main,
singleton::instance has to be called during static data initialization, and
static_init GUARANTIES that this static initialization will be performed
before main WITH NO additional calls.

>> If the constructor of the object depends on
>> other singletons, then instance() of those other singletons
>> will naturally be called before, and therefore they
>> will end up being constructed before.

You're right, if you refer to singleton A's before creating singleton B's
instance, to order of initialization would be correct. But let's no limit
this case to singletons only, where initialization is achieved in just one
call. There can many many different situation when you have to perform some
additional data initialization and manipulation before creating singleton
instance. Where would you put this code? Would you make singleton
constructor or instance access method dependent on all this data when it
naturally should not be?
Anyway it doesn't solve the problem for the first call to a singleton if it
has to be initialized before main. Unless you create a global static
variable and make the first call to singleton during this variable
initialization, but then you still need to refer to this variable from the
code somewhere in order to make sure your compiler does not eliminate it
due to optimization reasons, and this way you will introduce unnecessary

3. There is no construction recursion. If you did notice it somewhere,
please point to exact place.

4. Static data construction order is undefined by C++ standard fixing it
requires either changing the standard or getting rid of class and global
static data.

So, again, to make the idea crystal clear, the initial goal was:
1. Guarantee that static constructor method is called before main is
2. No additional calls in either global or any local scope
should precede static constructor invocation in order not to introduce
extra dependencies and eliminating a situation when
initialization invocation code does not get called for any reason.
3. Provide a way to control the order of static constructors calls. No
recursions are allowed.

The described approach fully satisfies the three simple requirements. If
anybody sees possible errors or ways to improve it, feedbacks are very

Thank you.

With best regards,
        Alexander Stoyan

Boost list run by bdawes at, gregod at, cpdaniel at, john at