Pelle Beckman wrote:
Hi,
I've done some progress in writing a rather simple
singleton template.
However, I need a smart way to pass constructor arguments
via the template.
I've been suggested reading "Modern C++ Design" or similar
books, but I feel there are full of clever guys here
who could help me out.
Also, c++ experts seem to have this kinky obsession with
references instead of pointers, so if you have
a argument (and implementation) for using them, please
tell me.
Here's what I've done so far.
template<class T>
class Singleton {
public:
T* Instance ();
void Release ();
Singleton ();
~Singleton ();
private:
static T* m_singleton;
};
template<class T> T* Singleton<T>::m_singleton = 0;
template<class T>
Singleton<T>::Singleton () {
}
template<class T>
Singleton<T>::~Singleton () {
// ...
}
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;
}
Thanks.
-- Pelle
A Singleton should not have public constructors as in your above class.
If this is a singleton wrapper class, then IMHO, it's not practical to
create a singleton that requires constructor arguments.
You're singleton should also have copy constructor and assignment
operator private or protected.
It should also have the destructor private or protected, however some
compilers like VC++ have problems compiling class with private or
protected destructors.
The following Singleton wrapper class has protected destructor. It
should compile on any compliant compiler, and it also compiles on VC++
6.0
Using this wrapper class you can make any class a singleton by either
inheriting from the Singleton wrapper class, or by calling
Singleton::Instance with a template type.
#include <stdlib.h>
template<typename T>
class Singleton
{
protected:
Singleton(){}
~Singleton(){}
Singleton(const Singleton&);
Singleton& operator=(const Singleton&);
public:
class FriendClass
{
public:
FriendClass():m_MyClass(new T()){}
~FriendClass(){delete m_MyClass;}
T* m_MyClass;
};
static T& Instance() {
static FriendClass Instance;
return *Instance.m_MyClass;
}
};
class Widget {
private:
Widget(){}
~Widget(){}
Widget& operator=(const Widget&);
Widget(const Widget&);
public:
friend class Singleton<Widget>::FriendClass;
int m_i;
};
class foo : public Singleton<foo>{
private:
foo(){}
~foo(){}
foo& operator=(const foo&);
foo(const foo&);
public:
friend class FriendClass;
int m_i;
};
int main(int argc, char* argv[])
{
Widget& MyWidget = Singleton<Widget>::Instance();
foo& Myfoo = foo::Instance();
system("pause");
return 0;
}