I have a question about the singleton pattern.
I saw two cases concerning the static member in the singleton class.
First it is an object, like this
class CMySingleton
{
public:
static CMySingleton& Instance()
{
static CMySingleton singleton;
return singleton;
}
// Other non-static member functions
private:
CMySingleton() {} // Private constructor
~CMySingleton() {}
CMySingleton(const CMySingleton&); // Prevent copy-construction
CMySingleton& operator=(const CMySingleton&); // Prevent assignment
};
One is an pointer, like this
class GlobalClass
{
int m_value;
static GlobalClass *s_instance;
GlobalClass(int v = 0)
{
m_value = v;
}
public:
int get_value()
{
return m_value;
}
void set_value(int v)
{
m_value = v;
}
static GlobalClass *instance()
{
if (!s_instance)
s_instance = new GlobalClass;
return s_instance;
}
};
What’s the difference between the two cases? Which one is correct?
You should probably read up Alexandrescu’s book.
Regarding the local static, I haven’t use Visual Studio for a while, but when compiling with Visual Studio 2003, there was one local static allocated per DLL… talk about a nightmare of debugging, I’ll remember that one for a while :/
1. Lifetime of a Singleton
The main issue about singletons is the lifetime management.
If you ever try to use the object, you need to be alive and kicking. The problem thus come from both the initialization and destruction, which is a common issue in C++ with globals.
The initialization is usually the easiest thing to correct. As both methods suggest, it’s simple enough to initialize on first use.
The destruction is a bit more delicate. global variables are destroyed in the reverse order in which they were created. So in the local static case, you don’t actually control things….
2. Local static
What’s the problem here ? Let’s check on the order in which the constructors and destructors are called.
First, the construction phase:
A globalA;is executed,A::A()is calledA::A()callsB::B()A::A()callsC::C()It works fine, because we initialize
BandCinstances on first access.Second, the destruction phase:
C::~C()is called because it was the last constructed of the 3B::~B()is called… oups, it attempts to accessC‘s instance !We thus have undefined behavior at destruction, hum…
3. The new strategy
The idea here is simple. global built-ins are initialized before the other globals, so your pointer will be set to
0before any of the code you’ve written will get called, it ensures that the test:Will actually check whether or not the instance is correct.
However has at been said, there is a memory leak here and worst a destructor that never gets called. The solution exists, and is standardized. It is a call to the
atexitfunction.The
atexitfunction let you specify an action to execute during the shutdown of the program. With that, we can write a singleton alright:First, let’s learn more about
atexit. The signature isint atexit(void (*function)(void));, ie it accepts a pointer to a function that takes nothing as argument and returns nothing either.Second, how does it work ? Well, exactly like the previous use case: at initialization it builds up a stack of the pointers to function to call and at destruction it empties the stack one item at a time. So, in effect, the functions get called in a Last-In First-Out fashion.
What happens here then ?
Construction on first access (initialization is fine), I register the
CleanUpmethod for exit timeExit time: the
CleanUpmethod gets called. It destroys the object (thus we can effectively do work in the destructor) and reset the pointer to0to signal it.What happens if (like in the example with
A,BandC) I call upon the instance of an already destroyed object ? Well, in this case, since I set back the pointer to0I’ll rebuild a temporary singleton and the cycle begins anew. It won’t live for long though since I am depiling my stack.Alexandrescu called it the
Phoenix Singletonas it resurrects from its ashes if it’s needed after it got destroyed.Another alternative is to have a static flag and set it to
destroyedduring the clean up and let the user know it didn’t get an instance of the singleton, for example by returning a null pointer. The only issue I have with returning a pointer (or reference) is that you’d better hope nobody’s stupid enough to calldeleteon it :/4. The Monoid Pattern
Since we are talking about
SingletonI think it’s time to introduce theMonoidPattern. In essence, it can be seen as a degenerated case of theFlyweightpattern, or a use ofProxyoverSingleton.The
Monoidpattern is simple: all instances of the class share a common state.I’ll take the opportunity to expose the not-Phoenix implementation 🙂
What’s the benefit ? It hides the fact that the state is shared, it hides the
Singleton.Singletonby a call to aFactoryfor example)deleteon your singleton’s instance, so you really manage the state and prevent accidents… you can’t do much against malicious users anyway!5. Last word
As complete as this may seem, I’d like to point out that I have happily skimmed any multithread issues… read Alexandrescu’s Modern C++ to learn more!