16.1.3.  qApp and Singleton Pattern

[ fromfile: singleton.xml id: singleton ]

As discussed earlier, the Singleton pattern is a specialized factory used in situations where we wish to limit the number or type of instances created.

The CustomerFactory::instance() method, defined in Example 16.7, is an example of a singleton factory. It creates an object if needed, but only the first time that the method is called. On subsequent calls it always returns a pointer to the same object.

Example 16.7. src/libs/customer/customerfactory.cpp

[ . . . . ]

CustomerFactory* CustomerFactory::instance() {
    static CustomerFactory* retval = 0;
    if (retval == 0) retval = new CustomerFactory(qApp); 1
    return retval;
}

1

Ensures this object and all its children are cleaned up when the QApplication exits.


It is important when dealing with heap objects that you do not leave memory leaks behind. You can use QObject's parent-child relationship to help in this regard.

As mentioned earlier, qApp is a pointer to a singleton instance of QApplication, which was presumably created in main(). The QApplication instance exists precisely as long as the application is running.

[Important] Why Not Use a static Parent?

If you make the parent of your heap objects a static QObject, children of this object will be destroyed after the QApplication is destroyed. Unless there is a compelling reason to the contrary, a program should not do anything with QObjects after the QApplication has been destroyed – including object cleanup. Static objects from different files of a multifile application are destroyed in a linker-dependent order. That order of destruction may cause unintended side-effects (e.g., segmentation faults at termination). See Section 8.6 for more details.