PDA

View Full Version : purpose of Q_GLOBAL_STATIC



raj_iv
15th July 2011, 11:08
Whats the purpose of Q_GLOBAL_STATIC macro and why it is used for.
Please follow thru some example.

MarekR22
15th July 2011, 12:03
When I taken a look how it looks like (http://qt.gitorious.org/qt/qt/blobs/4.7/src/corelib/global/qglobal.h#line1760), it looks like it is working for singletons.
First call of function NAME will cause creation of singleton and return pointer to that singleton.
During application clean up this singleton still can be used. In case it was already destroyed function NAME will return null pointer (this will prevent use of dangling pointer).

Macro is not documented so it shouldn't be used.

I have doubts how it should be used. Problem is with static keyword.
If macro is used outside of class in header file it will not be singleton, you will have one instance for each cpp file that included that header.
If macro is used outside of class in source file it will be visible only in that cpp file.
If used inside of class this will define inline static method className::NAME so again you will have multiple instances for each use of this method.
So it doesn't look like this macro is very useful. Only in case when you want have singleton visible only in single source file.

nightghost
15th July 2011, 14:07
look at QThreadPool::globalInstance Its implemented with the macro. it can be used (short example) like this:

header:



class Example {

static Example* globalInstance();
};


in cpp




Q_GLOBAL_STATIC(Example, theInstance);

Example* Example::globalInstance() {
return theInstance();
}

raj_iv
15th July 2011, 14:20
thanx MarekR22

yes i m using this macro only in case when i want to have singleton visible only in single source file(.cpp).

as u said :-)