[Qt-interest] Global variables "the Qt way"

Konrad Rosenbaum konrad at silmor.de
Wed Jun 16 18:52:55 CEST 2010


On Wed, June 16, 2010 17:18, Sensei wrote:
> Hi! I am in starting a new project, and I have a simple question about
> "global" variables, obviously not a C++ question! :)
>
> What is the "Qt way" of handling global variable?

The same as C++ if no better alternative is obvious.

> I'll explain with an example. My application has a QApplication "global"
> variabel qApp, always accessible.

It's actually a macro to QCoreApplication::instance() which returns the
application object singleton.

If you plan to implement singleton behavior (only one instance of the
class), then I recommend to copy this pattern.

> What do you recommend I do for, let's
> say, a settings instance?

Here you are suffering from bad choice of examples: QSettings is
programmed in a way that makes it easier to create a local instance on the
stack each time you access the settings.

> This should be accessed by all (many) other
> classes, but I find that simply having a header defining variables with
> external storage, a little ugly.

For simple objects that don't need much initialization this is actually
the best solution: try to avoid global pointers - they tend to bite in
unpredictable ways. If it is possible to implement an object as a global
instance without causing any headaches because of dependencies, then this
is the way to go.

Eg. I often have something like this in my projects:
extern QString pathToMyVerySpecialFiles;
which I then initialize in main() before anything important happens.

If the object is more complex a singleton is often the best way to go.
Depending on whether you want lazy or predictable instantiation the static
instance() method may differ.

Lazy: only instantiate the first time you need it
static QPointer<MyClass> MyClass::m_inst;
MyClass::instance(){
  if(m_inst.isNull())m_inst=new MyClass;
  retun m_inst;
}
Note that this is usually not thread safe or at least is difficult to do
in a thread safe way.

Predictable: you know exactly when it happens
static QPointer<MyClass> MyClass::m_inst;
MyClass::instance(){return m_inst;}
MyClass::initialize(){if(m_inst.isNull())m_inst=new MyClass;}
with initialize being called at the point where/when you want it to
happen. If done early enough this is quite safe, otherwise you run the
risk of getting a NULL-pointer from instance().

Creating a macro that makes the instance() method look like a global
variable is left as an exercise to the reader... ;-)


    Konrad




More information about the Qt-interest-old mailing list