Click here to Skip to main content
15,879,326 members
Articles / Programming Languages / C++
Article

A Singleton Template Class

Rate me:
Please Sign up or sign in to vote.
3.29/5 (21 votes)
19 Mar 20032 min read 153.5K   2K   30   22
A Singleton Template Class

Introduction

There are times, when you need to have a class which can be instantiated once only. The Singleton Design Pattern provides a solution for such a situation.

There are several possible ways to implement a singleton pattern, but it all pretty much comes down to a class that has a private constructor and a static member function to create and retrieve an instance of the class. My implementation does not differ much from this scenario, with the exception that I created a singleton template class.

So, why a template class?

Well I have searched the Internet for an elegant implementation of a singleton class but I did not really find a solution to my satisfaction. Most classes I found consist of a Singleton base class that you can use to derive your own singleton class from. The problem with most of these classes is the fact that you still have to override the GetInstance function to return a pointer to your derived class. A template base class does not have this limitation as I can return any type of pointer.

How it works

To prevent outside source from creating (or copying) an instance of our singleton class, we need to shield the constructor and copy constructor of the singleton class. Further we need to provide a method to create and retrieve a reference to the singleton object:

C++
static T* Instance()
{
if (m_instance == NULL) m_instance = new T;
            ASSERT(m_instance != NULL);
return m_instance;
};

When this method is called for the first time, it creates an instance of the singleton class, any sequential calls will return a reference to the created class instance. To get a reference to the singleton object, all we have to do is call this method as following:

C++
CMySingleton* mySingleton = CMySingleton::Instance();

That is almost all that there is to it. Next to shielding the constructors, I also shielded the destructor, so the singleton class cannot be deleted by accident. Just call the DestroyInstance() method to destroy the singleton object. However, be careful when to call this method, because after you have called this method, all your class data will be destroyed and a sequential to the Instance() method will create a new instance.

So how do you create a class derived from the singleton template class? Again there is nothing to it. Just include the attached header file and create your object as following:

C++
class CMySingleton : public CSingleton<CMySingleton>
{
    friend CSingleton<CMySingleton>;   
 
       private:      

           CMySingleton();
           ~CMySingleton();
 
    ...
}

Conclusion

This implementation of the Singleton Pattern makes creating your own singleton class incredibly easy. But you do have to be careful when to destroy the singleton class instance. If you find this to be a problem you could consider adding (automatic) reference counting.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Netherlands Netherlands
Brian van der Beek has been working as a software engineer at Philips TASS since 1999. He worked on a Digital Video Broadcasting system based on COM components. After that he has worked on test and factory equipment for DVD+RW drives. And since the last 2 year he is working on firmware for the Philips/BenQ Blu-ray drive.

Comments and Discussions

 
QuestionAnother possibility Pin
James_7225-Jul-11 19:03
James_7225-Jul-11 19:03 
GeneralSingleton flawed Pin
Mark Ginnane24-Jul-10 15:03
Mark Ginnane24-Jul-10 15:03 
GeneralI want to subclass CMySingleton but I'm having problems... Pin
Demented-TED24-Mar-09 19:06
Demented-TED24-Mar-09 19:06 
Questionwont compile on vs2005. Pin
miche_mannen26-Sep-07 9:39
miche_mannen26-Sep-07 9:39 
Generalimplemetation Pin
Paul the Great18-Sep-07 1:33
Paul the Great18-Sep-07 1:33 
GeneralSimilar threadsafe (+older) article: Pin
Paul Evans9-Nov-03 21:51
Paul Evans9-Nov-03 21:51 
GeneralYour sample makes you still have to destroy the Singleton. Pin
WREY6-Jul-03 12:01
WREY6-Jul-03 12:01 
GeneralRe: You sample makes you still have to destroy the Singleton. Pin
Brian van der Beek6-Jul-03 20:34
Brian van der Beek6-Jul-03 20:34 
GeneralRe: Your sample makes you still have to destroy the Singleton. Pin
WREY7-Jul-03 0:34
WREY7-Jul-03 0:34 
I don't know if you mean the idea of a Singleton is flawed, or the idea of it destroying itself, is flawed.

Personally, I don't believe neither is, because there are times when you need to work with an object that you want to know for sure, ONLY ONE EXISTS!! The Singleton fills that requirement.

The other thing you need to know, is that the Singleton has the capacity to destroy itself; thereby relieving you of all responsibilities of worrying when you ought to destroy it.

Those two requirements are not just nice features to have, they are something you expect the Singleton to provide, and Alexandrescu goes to extra length of certifying in all his examples that none of these qualities are missing.

For the beginner, getting to learn about this pattern seems easy and almost trivial at the start, but as you become more aware of its uniqueness and power, you begin to realize how really difficult it is to use at times, particularly in a multithreaded environment when your reliance is counting on the fact that some other thread cannot create another Singleton.

The opposite side to that concern, is that you don't want to have to worry either about destroying the Singleton object too early while another thread might be using it. This is where Alexandrescu insist that a genuine Singleton, must know when to destroy itself, using the mechanism of the language itself (and to that end, he gave an example of how this can be accomplished in his book, of which I have already quoted).

To say it is a nice feature, but not mandatory, is just as good as saying you don't need a way of controlling multiple threads from colliding with each other and doing damage.

Smile | :)

William

Fortes in fide et opere!
GeneralArticle updated: Pin
Brian van der Beek20-Mar-03 20:58
Brian van der Beek20-Mar-03 20:58 
GeneralDoes not fully implement the singleton pattern I'm afraid Pin
Jörgen Sigvardsson20-Mar-03 13:05
Jörgen Sigvardsson20-Mar-03 13:05 
GeneralRe: Does not fully implement the singleton pattern I'm afraid Pin
Jim A. Johnson20-Mar-03 13:53
Jim A. Johnson20-Mar-03 13:53 
GeneralRe: Does not fully implement the singleton pattern I'm afraid Pin
Jörgen Sigvardsson20-Mar-03 22:24
Jörgen Sigvardsson20-Mar-03 22:24 
GeneralRe: Does not fully implement the singleton pattern I'm afraid Pin
Brian van der Beek20-Mar-03 20:31
Brian van der Beek20-Mar-03 20:31 
QuestionUhhhhh? Singleton Template? Pin
Anonymous20-Mar-03 12:37
Anonymous20-Mar-03 12:37 
AnswerRe: Uhhhhh? Singleton Template? Pin
Brian van der Beek20-Mar-03 20:14
Brian van der Beek20-Mar-03 20:14 
GeneralRe: Uhhhhh? Singleton Template? Pin
Anonymous21-Mar-03 8:16
Anonymous21-Mar-03 8:16 
GeneralIf templates are your thing Pin
Barry Lapthorn20-Mar-03 11:58
protectorBarry Lapthorn20-Mar-03 11:58 
GeneralRe: If templates are your thing Pin
João Paulo Figueira20-Mar-03 13:02
professionalJoão Paulo Figueira20-Mar-03 13:02 
GeneralRe: If templates are your thing Pin
Jörgen Sigvardsson20-Mar-03 13:11
Jörgen Sigvardsson20-Mar-03 13:11 
GeneralRe: If templates are your thing Pin
Peter Hancock20-Mar-03 13:35
Peter Hancock20-Mar-03 13:35 
GeneralRe: If templates are your thing Pin
Brian van der Beek20-Mar-03 20:11
Brian van der Beek20-Mar-03 20:11 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.