How to set object to nullptr after self deletion

Viewed 279

I have a dialog window with a class of QDialog. I declare it in the header files with:

MyDialogClass myDialogWindow = nullptr;

and create the window on runtime somewhere with

myDialogWindow = new MyDialogClass(this);

It is also delf destroying, because of it's attributes:

this->setAttribute(Qt::WA_DeleteOnClose);

Does anyone now how can I set the myDialogWindow pointer to nullptr after the self deletion without connection signals?

Thanks in advance.

3 Answers

This isn't possible without some signal or event logic. The object does not own the pointer, the pointer is pointing at the object.

However you can use a QPointer which wraps the signal handling and nulling for you.

QPointer<MyDialogClass> myDialogWindow;
myDialogWindow = new MyDialogClass(this);
myDialogWindow->setAttribute(Qt::WA_DeleteOnClose);

// some time later, check dialog has not been closed
if( ! myDialogWindow.isNull() )
{
    // do something with dialog
}

You can catch when the object is destroyed, and erase the pointer.

connect(myDialogWindow, &QObject::destroyed, [&myDialogWindow](){ myDialogWindow = nullptr;});

You can't do that in general. Any T cannot know whether it is being used as T or T& or T*, and you can't automatically change all relevant T* to nullptr from inside T (because it doesn't know about them).

You need some other way to be informed that your MyDialogClass instance was destroyed - a signal for example.

Related