Solving order of initialization:
First off this is just a work around becuase you have global variables, that you are trying to get rid of but just have not had time yet (you are going to get rid of them eventually arn't you :-)
class A
{
public:
// Get the globale instance abc
//
static A& getInstance_abc() // return reference.
{
static A instance_abc;
return instance_abc;
}
};
This will gurantee that it is initialised on first use and destroyed when the application terminates.
Multi Threaded Problem.
The language does not offically gurantee that the construction of ststaic function objects is thread safe (note the language gurantees nothing about threads). So technically the getInstance_XXX() method must be guarded with a critical section. On the bright side gcc has an explicit patch as part of the compiler that gurantees that each static function object will only be initialized once even in the presence of threads.
Please note:
DO NOT use the double checked locking pattern to try an optimize away the locking. This will not work in C++
Creation Problems:
On creation there are no problems because we garantee that it is created before it can be used.
Destruction Problems:
There is a potential problem of accessing the object after it has been destroyed. This only happens if you access the object from the destructor of another global variable (by global I am refering to any non local static variable).
Solution you must make sure you force the order of destruction.
Remember the order of destruction is the exact inverse of the order of construction. So if you access the object in your destructor you must gurantee that the object has not been destroyed. To do this you must just gurantee that the object is fully constructed before the calling object is constructed.
class B
{
public:
static B& getInstance_Bglob;
{
static B instance_Bglob;
return instance_Bglob;;
}
~B()
{
A::getInstance_abc().doSomthing();
// The object abc is accessed from the destructor.
// Potential problem.
// You must guarantee that abc is destroyed after this object.
// To gurantee this you must make sure it is constructed first.
// To do this just access the object from the constructor.
}
B()
{
A::getInstance_abc();
// abc is now fully constructed.
// This means it was constructed before this object.
// This means it will be destroyed after this object.
// This means it is safe to use from the destructor.
}
};