c++qt

Is it necessary to delete dialog window pointer in Qt?


I use this code:

MyDialog *md = new MyDialog();
md -> show();

to open a dialog window in Qt. Will md be deleted automatically when the dialog window is closed or do I need to run delete md when the window is finished?


Solution

  • Yes. Unless you pass this while this is a QWidget or any other QWidget:

    MyDialog *md = new MyDialog(this);
    md->show();
    

    you need to:

    delete md;
    

    at some point in order to release its memory. Also you need to make sure in this case that the object tree is well linked. What you can also do is call setAttribute(Qt::WA_DeleteOnClose); on md so that when you close the dialog, its memory will also be released as Zlatomir said. However if you need md to live after it was closed setAttribute(Qt::WA_DeleteOnClose); is not an option. This is also dangerous and could lead to access violation/segmentation fault if you are not careful.