C++ Singletons

One of the first rules you learn when programming is not to use global variables. Sometimes it’s possible and sometimes it’s not. I believe that every rule has an exception, <– this too. But the thing is that if you code in C++, you say to yourself, let’s encapsulate it all in a class. How nice, huh? Thing is that from the beginning you knew that those variables should be global, to something. Everything is in relation. Certainly not all functions will use the globals. The real example I encountered was to use the AllocConsole API for creating a console screen for my process. The system allows for every process to have at most one console, so obviously wrapping it in a singleton class is a good move. That class will contain also some variables which hold the state of the console. Let’s spare the gross details for now…

So having the variables inside the class as a namespace led me to touch the variables as:

void MainClass() 
{ 
 Console::m_staticVariable = ... 
}

Then I found myself accessing that variable from the MainClass, and I understood that I should move some code from MainClass to the Console class. Hey, you can say that I designed the whole thing wrong from the first moment. But believe me, sometimes you just have that piece of code which might lie in both classes. Eventually you have to decide where it fits better. Even though after some coding I was satisfied with my code, all the methods were static as well, otherwise I can’t access the so called globals. Although, this time the globals are in a namespace, that’s a start. Noticing that all Console’s methods were static, I got disgusted at my own code. Seriously, that happens to me too ;) As long as you don’t commit the code, you are allowed to go all the way until you are satisfied and the code is to your liking. At least this is what I think.

So… singleton was my answer, of course.

The “standard” basic pattern for a singleton would be to make the constructor private and have a getInstance method which will return the one and only instance of the singleton class in the system. It looks something similar to:

class MyClass {
private:
MyClass() { … }

public:
static MyClass& getInstance()
{
 static MyClass instance; // This is all the trick.
 return instance;
}

};

Speaking technically the way the static is implemented in Assembly is just setting a boolean with true when you create the object the first time and even register its corresponding destructor to the _atexit CRT function. I found it interesting.

Here it is in a nutshell:

static MyClass& getInstance() 
{ 
 static bool isInitialized = false; 
 if (!isInitialized) { 
  isInitialized = true; 
  g_MyClassInstance::MyClass(); 
  _atexit(g_MyClassInstance::~MyClass); 
 } 
 return g_MyClassInstance; 
}

 Static variables are not magic, you have to check whether they are already initialized or not. The generated code, is no brainer, and uses a boolean to check it out as well.

So off to the way I went, changing a few bits of my code to become a singleton. While testing my code again, I got a crash when the program was finished. Now quickly thinking, there’s something wrong with a “destroy” code, either destructor or something similar doesn’t function well. Well, looking at my MainClass dtor I noticed that I have to control the death of the Console class. Note that when calling the getInstance method the first time of a singleton it will only then get initialized. So you are guaranteed when the singleton-instance is constructed but you don’t know when it will be destructed. Doh.

Well, let’s go to business, implementing a dynamic singleton. To be honest, I have no idea how that’s officially called, I’m pretty sure someone already named it with something. Using the dynamic singleton I control both construction and destruction timings.

The first getInstance implementation that comes to mind is something like this:

MyClass& MyClass:getInstance() 
{ 
 static MyClass* instancePtr = NULL; 
 if (instancePtr == NULL) { 
  instancePtr = new MyClass(); 
  // error code for handling bad_alloc... 
 } 
 return *&instancePtr; 
}

Now you need a destroy method:

void MyClass:Destroy() 
{ 
 ASSERT(instancePtr != NULL); // No no. 
 delete instancePtr; 
 instancePtr = NULL; 
}

Aha! Now notice how Destroy access instancePtr which was defined inside getInstance. Therefore, you have to move the pointer to be a static class member, how rude. But no biggy. Of course, you must not call Destroy from the destructor, to avoid recursion and bad stuff happening, in short. It is vital to remember to call Destroy, otherwise you are in big troubles. On the other hand, having C++ on our side, we can extend the code so it will use a sort of smart pointer that will know when to destroy the instance automatically. A static std::auto_ptr<MyClass> m_instancePtr, will certainly do the job.

Now you ask yourself, why the heck should I use the smart pointer mechanism if I want to control the construction and destruction of the singleton. Well that’s a good question, you have to consider multi-threading.

Some problems arise with singletons and multi-threaded applications. Even though my specific application was MT, I didn’t have to worry about the construction of the singleton instance because it was surely done before CreateThread was called. When you cannot be sure about that, you will have to protect the static instance on your own. But you cannot wrap the static declaration with acquiring any sort of a lock. Maybe with a nested anonymous scope? While I’m not really sure, it’s pretty ugly. So that’s why you need the smart pointer mechanism which will destroy the class on its own accord (assuming you don’t really care when) and you are the one who fully control the construction time…

Benny and the jets say hi.

Leave a Reply