P
Pelle Beckman
Hi,
I've just finished writing a template (whew!) and
would like some opinions on the design.
The goal was to be able to do fairly simple
singletons (no excplicit thread-safety, etc)
and keep it simple.
It's also supposted to give the ability to
do simple derived singletons - which is not
possible with my other attempts that were based
on the classical "global pointer to an object
which is set using 'this' in the objects constructor"
(I hope you understood that...).
Anyway, comments? suggestions?
I'm a bit unsure of the ()-operator - could
that get in the way of other functions, operators, etc?
template<class T>
class Singleton {
public:
T* Instance ();
void Release ();
T* operator() ();
Singleton () {}
private:
static T* m_singleton;
};
template<class T> T* Singleton<T>::m_singleton = 0;
template<class T>
T* Singleton<T>:perator() () {
return this->Instance ();
}
template<class T>
T* Singleton<T>::Instance () {
if (m_singleton == 0) {
m_singleton = new T;
}
return m_singleton;
}
template<class T>
void Singleton<T>::Release () {
if (m_singleton == 0)
return;
delete m_singleton;
m_singleton = 0;
}
The code allows me to do this:
Singleton<MyClass> mysingleton;
mysingleton ()-> AFunction();
mysingleton.Instance ()->AFunction();
which I find is rather nice.
-- Pelle
I've just finished writing a template (whew!) and
would like some opinions on the design.
The goal was to be able to do fairly simple
singletons (no excplicit thread-safety, etc)
and keep it simple.
It's also supposted to give the ability to
do simple derived singletons - which is not
possible with my other attempts that were based
on the classical "global pointer to an object
which is set using 'this' in the objects constructor"
(I hope you understood that...).
Anyway, comments? suggestions?
I'm a bit unsure of the ()-operator - could
that get in the way of other functions, operators, etc?
template<class T>
class Singleton {
public:
T* Instance ();
void Release ();
T* operator() ();
Singleton () {}
private:
static T* m_singleton;
};
template<class T> T* Singleton<T>::m_singleton = 0;
template<class T>
T* Singleton<T>:perator() () {
return this->Instance ();
}
template<class T>
T* Singleton<T>::Instance () {
if (m_singleton == 0) {
m_singleton = new T;
}
return m_singleton;
}
template<class T>
void Singleton<T>::Release () {
if (m_singleton == 0)
return;
delete m_singleton;
m_singleton = 0;
}
The code allows me to do this:
Singleton<MyClass> mysingleton;
mysingleton ()-> AFunction();
mysingleton.Instance ()->AFunction();
which I find is rather nice.
-- Pelle