Nominate our 2022 Qt Champions!

[solved] how to delete pointers before main() exits ?

  • Consider the next code:

    @int main(int argc, char *argv[]){
    QApplication app(argc, argv);

    QWidget * mainWindow = new QWidget;

    MyWidget * myW = new MyWidget;

    // some other code

    // delete mainWindow; //if I use delete, they destroy the widgets before I can use them
    // delete myW; // if not, a memory leak occurs... what should I do?
    return app.exec();

    When I run it my application runs just fine. But for the concept of allocating objects on the heap, I should manually delete the _mainWindow _and _myW _pointers.
    Problem is that if I call delete on these pointers anywhere in main() (f.e. before return), the object destructors are called too and my widgets get destroyed little time after creation without even being able to use them for a second. But if I don't call delete, I am creating a memory leak since the heap memory allocated for _mainWindow _and _myW _is not deleted.
    At this point I'm really stuck on how should I delete these pointers, I can't seem to find any good place to delete the pointers without destroying the widgets too... any suggestions ?

  • @
    int ret = app.exec();
    delete mainWindow;
    delete myW;

    return ret;

  • Two other options:

    1. Allocate your main window on the stack, e.g.:
      @QWidget mainWindow; // using a QWidget
      QMainWindow mainWindow; // or maybe a QMainWindow@

    2. Allocate your main window on the heap and call

    When it comes to your other widget, you can choose the same approach but if the widget is a child window to your main window a better approach is to create it using your mainWindow as a parent, e.g.:

    @// if mainWidget is allocated on the stack
    MyWidget *myW = new MyWidget(&mainWindow);

    // if mainWidget is allocated on the heap
    MyWidget *myW = new MyWidget(mainWindow);@

    Then your widget will be deleted just before your mainWindow (when your mainWindow deletes its children).

  • smart pointer can be used in such cases too, such as

    QScopedPointer<QWidget> mainWindow(new QWidget);

    QScopedPointer<MyWidget> myW(new MyWidget);

Log in to reply