Initialization and cleanup



  • I designed my app using Qt Designer. Where should I place the code for initialization and cleanup (best practice)? For example, where should establishing a network connection or database be and where should the clean up for those connections be.


  • Qt Champions 2016

    @WhatIf
    Hello,

    Short answer:
    Where they're used.

    Longer answer:
    When acquiring a resource (as a database connection) it a good idea to have that same class manage and free the resource - the ever-so-relevant RAII principle. Basically, every resource that you create and initialize, you free as well. Ordinarily, you wouldn't transfer the ownership of the resource, but there are exceptions. The resource you manage is usually exposed through the class' interface (the methods), so others can manipulate it.

    Kind regards.



  • What I was trying to get to is, for example, JSP has jspInit() for initialization and jspDestroy() for clean up. Does Qt have a similar approach to initialize code that will be used through out the life of the program and in different classes? Where should I do final clean up before the program ends?


  • Qt Champions 2016

    @WhatIf

    Does Qt have a similar approach to initialize code that will be used through out the life of the program and in different classes?

    Nothing to do with Qt actually. No, there is no special place for that. You initialize in main(), run your code in main(), and then clean up in main(). Or, since you're using an object-oriented language (i.e. C++), you create a few objects in main() and whatever resources they acquire in their constructors (or along the way), they clean up in the destructors (this is what RAII means). The only thing left to be done in main() is to clean those few objects if needed.

    Where should I do final clean up before the program ends?

    Before returning from main().


  • Lifetime Qt Champion

    Hi,

    Just a small correction, in order to use Qt's features like signals and slots you first need to create an instance of QCoreApplication and for GUI application depending on the type either a QGuiApplication or a QApplication.


  • Qt Champions 2016

    @SGaist, @WhatIf
    Ah, yes, I missed to mentioned that. The first QObject one creates should be the root QObject, that is one of the QCoreApplication hierarchy (with some very minor and irrelevant for this discussion exceptions). Still, one does create the application object in main(). :D


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.