Static singleton and Q_GLOBAL_STATIC
-
I'm trying to use this "macro ":http://lists.trolltech.com/qt-interest/2008-03/msg00022.html to define a static singleton of one class.
Here is what I wrote in MyClass.h
@class MyClass : public QObject
{
Q_OBJECTpublic:
MyClass();
void doSomething();
};Q_GLOBAL_STATIC(MyClass, myClassInstance)@
But then it creates two different instances when I use myClassInstance()->doSomething() in my mainwindow, and once more in a QDialog created from the mainwindow (same thread)
What's wrong? -
Hum, I changed it to:
MyClass.h
@class MyClass : public QObject
{
Q_OBJECTpublic:
MyClass();
static MyClass* instance();
void doSomething();
};@
and MyClass.cpp
@Q_GLOBAL_STATIC(MyClass, myClassInstance)MyClass *MyClass::instance()
{
return myClassInstance();
}@
Now, am I doing it right? -
Q_GLOBAL_STATIC should be in the .cpp file. Otherwise it would be compiled as often as the header file is included, resulting in the same amount of instances.
The instance() method isn't needed, I would say.
-
Dear Volker, considering that myClassInstance() is defined in the .cpp file, what method will you call if you remove the instance() one?
-
Ah, sorry. You'll need the instance() method, of course. The method defined by the macro is only visible in the .cpp file it is in. Sorry for the confusion.
-
Ok thanks for the clarification
-
I think the Q_GLOBAL_STATIC macro defines the myClassInstance method.
-
Yes it does.