The Singleton Pattern Revisited - The creation of a Singleton
(Page 2 of 5 )
Please read the other two articles about the Singleton Pattern if you haven’t already: http://www.devarticles.com/c/a/Cplusplus/C-plus-
plus-In-Theory-The-Singleton-Pattern-Part-I/ and http://www.devarticles.com/c/a/Cplusplus/C-plus-plus-In-Theory-The-
Singleton-Pattern-Part-2/. This article will deal with the generic Singleton implementation as it was presented in the second article. I find this implementation to be the most useful; the other code examples in the previous articles just serve to create a better understanding of how and why we want to use singletons.
The question the reader raised also concerned this code. How can we successfully create a singleton when the constructor for the object contained in that singleton needs parameters that are determined dynamically at run-time? First, here is a quick recap of that generic Singleton implementation:
#ifndef __SINGLETON_H
#define __SINGLETON_H
template <class T> struct CreateLeaking {
static T* Create() { return new T; }
};
template <class T> struct CreateMeyers {
static T* Create() {
static T _instance;
return &_instance;
}
};
template < class T,
template<class> class CreationPolicy=CreateMeyers >
class Singleton {
public:
static T& Instance() {
if (!m_pInstance)
m_pInstance=CreationPolicy<T>::Create();
return *m_pInstance;
}
};
private:
Singleton(); // hidden
Singleton(Singleton const&); // hidden
Singleton& operator=(Singleton const&); // hidden
static T* m_pInstance;
};
template <class T, template <class> class C>
T* Singleton<T,C>::m_pInstance=0;
#endif // __SINGLETON_H
This class is very useful because it truly promotes code reuse, in the sense that any class you already have can be made a Singleton… or can it?
The code above is not sufficient when the class you want to make a singleton doesn’t supply a default constructor, but one that needs parameters instead. You can see that the compiler will complain when the Create() function in either policy class wants to construct it without providing the necessary parameters. How do we convey that information to the right constructor then?
Don’t add a default constructor to the class you want to use as a Singleton. This defies the point of creating a generic Singleton class in the first place, and it might not always be possible to change the code! Let’s take a closer look at this creation policy thing first.
Next: Policy-based Class Design >>
More C++ Articles
More By J. Nakamura