How to: convert any class to a Singleton with a template wrapper in C++

The singleton design pattern aims to give you a single instance of a class, and provide global access to it. Not two copies, not five, ONE copy – and one copy only. This is pretty useful when you have things in your code where you only ever want a single copy to exist, like a logging subsystem, or audio subsystem or what-have-you.

Why bother?

Why not just create a single instance of the class? Well yeah, you could, but where are you going to place the declaration? In the main so it’s globally declared? Global variables are bad-design like goto statements, and modern languages like C# don’t even have the facility to use global vars (deliberately removed to prevent misuse). Also, if you use a global instance it’s going to be instantiated as soon as the line of code to instantiate it is hit, which means you could be creating your instance (which might rely on other instances) before one of them is ready (for example, starting up a AI subsystem before a random number generator is seeded). You could swap initialisation orders around until you’re blue in the face, but it’s more work for you, and sooner or later you’re probably going to hit a chicken-and-egg scenario where one class requires another initialised first and vice-versa.

Okay, so how about a pointer to a static instance? This will define the object globally and defer instantiation until a time of your choosing, but you’re still using a global variable. And that’s something we really want to avoid. So what else is there? As you might have guessed, this whole tangle gets elegantly sorted out by the singleton design pattern.

Dinner for One

One of the best pages for singleton examples I’ve seen so far is this: http://www.yolinux.com/TUTORIALS/C++Singleton.html, and within the page they give a recipe for a templatised version so you can turn any class into a singleton which is responsible for its own instantiation and instance-limiting in a super-easy way – check it out:

Dump the above into a file called Singleton.hpp and include it in your project – now let’s take it for a spin…

Example Usage

Once you’ve got your templated singleton wrapper (above), we can start applying it to some classes. The four main things we have to do are:

  1. Include our templated singleton wrapper, i.e.:
  2. Perform a global typedef (not global variable/object/instance – just a typedef) which creates us a templatised singleton version of our class(es) – i.e.:
  3. Access our instance via the SingletonTypedef::instance method, i.e.:
  4. And finally, destroy the instance before the program terminates, i.e.:

Here’s some example code which puts it all together with two simple place-holder classes:

Pretty neat, huh?

Cleanup

As long as you remember to call the destroy function at the end of your code there’ll be no memory leaks or any “still reachable” memory for the OS to clean up. But how to be sure? Because if you valgrind the above code (via the alleyoop front-end, in this instance) you get this:

Alleyoop - No memory leak

Not too shabby at all.

Only, the thing is, during the creation of this article I’ve been reading things about Singletons. Bad things. Things that make me think they’re not the great idea I thought they were. Have a look at the article “Singleton, I love you but you’re bringing me down” over at CodingWithoutComments if you’re interested.

It seems that just a single instance of a class with a class factory to create the object (hence separating logic and instantiation) is really the way to go.

Oh well. It was nice while it lasted…

3 thoughts on “How to: convert any class to a Singleton with a template wrapper in C++”

  1. Good post.

    Also it is important to remember that the Singleton template also doesn’t work in distributed or clustered environments. Some servlet containers like JBoss have their own implementation which is guaranteed to work across distributed/clustered environments and are also thread safe too.

    Caveats…
    Yes, I know this is Java not C++
    Yes, I know we’re talking about being contained in servlet containers not stand alone apps

    Citation needed! OK, check out how clean this code looks in comparison…
    How to: implement singleton EJB in JBoss
    http://www.theserverside.com/news/1363656/New-Features-in-EJB-31

    Looks like you’re doing good work, keep it up.
    Also consider reading Head First Design Patterns [Paperback]

    1. The JBoss code is indeed very clean, like it.

      I was aware of the threading issues with Singletons (and I’d googled about a bit regarding it), but I’m not overly concerned at the moment as I’m not using threads. If it came to it, you could always use a boost::mutexed_singleton in a multi-threaded or clustered environment, but for now it’s not as much a deal-breaker as the entire concept being a bit sketchy =P

      The Head First book looks decent too – will try to pick up a copy and keep the GoF book for reference.

      Cheers for the feedback!

Leave a Reply

Your email address will not be published.