Important: Please read the Qt Code of Conduct -

Where to call destructor for new in main()

  • Hello,

    i have kind of a noob question.

    if a allocate an object (SomeObject) in the main() function. Where do i call the destructor on application closing.

    int main(int argc, char *argv[]){
        QApplication a(argc, argv);
        MainWindow w;
        SomeObject* so =  new SomeObject();
        return a.exec();

  • Lifetime Qt Champion

    u can split return a.exec();
    so its

    auto code = a.exec();
    delete xxxxx
    return code;

    But you can also do
    SomeObject so; // no need for new

    as main is not running out of scope until exec() exits.

    Also say it was QButton and u new one and give it to say a Dialog, then dialog will delete it. All widgets are deleted by their owner/parent.
    You own class if not QObject will ofc. not.

  • @mrjj Thanks

Log in to reply