16.1.3.  qApp and Singleton Pattern

[ fromfile: singleton.xml id: singleton ]

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.


[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.