Hi all:
I am writing a library of utility classes, many of which are singletons. I have implemented them as such using inheritance:
template <class T>
class Singleton {
public:
T& getInstance() {
if(m_instance == 0) {
m_instance = new T;
}
return m_instance;
}
private:
static T* m_instance;
};
class SomeClass : public Singleton<SomeClass> {
public:
SomeClass() {}
virtual ~SomeClass() {}
void doSomething() {;}
};
Obviously this is a simple example, not an actual class. Anyways, I am finding that using code such as:
SomeClass::getInstance().doSomething();
Will create more than one instance of SomeClass. I am thinking this may be due to the fact that it is being used outside my library (.a) file as well as internally. For example, I am using a UI library not written by myself which is separately compiled and to which I am making additions. Some of these additions utilize singletons which are also being used in my .a library.
Is the separate compilation causing this? Something else?
The only way I have managed to get around the issue is to create a global object in my main.cpp file which I initialize with any singletons I will need. Then all code accesses this common global object with calls such as:
GlobalObject::getSomeClass().doSomething()
I hate having to add an additional method to this object every time I create another singleton. Plus the syntax seems clearer and more familiar using the first access method:
SomeClass::getInstance().doSomething();
Please let me know if you have any thoughts, opinions, etc.
Thanks.