sadly it seems there is no way to invoke a static method without a previous instance of the class.
That's not true at all. Static methods do not require any class instance to invoke. You use the syntax:
result = MyClass::myStaticMethod();
result = MyClass::myStaticMethod();
To copy to clipboard, switch view to plain text mode
A common way to implement a Singleton class is to use a static class method along with a static pointer:
// MyClass.h
class MyClass
{
private:
MyClass * pInstance;
MyClass();
~MyClass();
public:
static MyClass * instance()
{
if ( !pInstance )
pInstance = new MyClass();
return pInstance;
}
};
// MyClass.cpp;
MyClass::pInstance * instance = 0;
MyClass * pSingleton = MyClass::instance();
// MyClass.h
class MyClass
{
private:
MyClass * pInstance;
MyClass();
~MyClass();
public:
static MyClass * instance()
{
if ( !pInstance )
pInstance = new MyClass();
return pInstance;
}
};
// MyClass.cpp;
MyClass::pInstance * instance = 0;
MyClass * pSingleton = MyClass::instance();
To copy to clipboard, switch view to plain text mode
This leaves a dangling pInstance memory leak when the program exits, but you can implement code to clean that up if necessary.
Bookmarks