H i, everyone.
I wrote a simple template Singleton class, like the following:
template<typename T>
class Singleton
{
public:
static T& getInstance () {return ms_instance;}
static T ms_instance;
};
template<typename T>
T Singleton<T>::ms_instance;
and I also wrote some subclass, such as:
class A
: public Singleton<A>
{
public:
A ()
{
cout << "xxx" << endl;
}
};
What I want to do is calling A's ctor when I declear class A, but the above code doesn't work. I don't use A explictly elsewhere.
I found 2 ways to slove it. The first is explicitly defining A::ms_instance, and the second is simply code it in the Singleton's ctor, like the following:
...
Singleton ()
{
ms_instance;
}
...
Now, I have 2 questions.
Why does the second way work?
If I have many subclass, what's the order of their initialization? In order to facilitate understanding, I'll give an example.
class A : Singleton<A> { public: A () { cout << "A" << endl; } }; class B : Singleton<B> { public: B () { cout << "B" << endl; } }; class C : Singleton<C> { public: C () { cout << "C" << endl; } }; ... //when the application runs, does it output ABC, CBA or indeterminacy?
Thanks in advance.