Question

I am developing a gui proram using Qt 4.7.4 (64 bit). I have tried to isolate the problem as follows:

I have a window: class PreferencesWindow : public QMainWindow and in another class I initialize and show it as

QSharedPointer<PreferencesWindow> pPreferencesWindow = QSharedPointer<PreferencesWindow>(new PreferencesWindow());
pPreferencesWindow->show();

it is all good, then I close the window either by pressing ESC or clicking the x button on the window. And then I call

QApplication::quit();

to terminate the whole program. It terminates but gives a segmentation fault just before terminating.

The question here is why it terminates cleanly when I use regular pointer instead of QSharedPointer and how to use QSharedPointer properly in this case?

Was it helpful?

Solution

I suspect the problem is that when you close the window, the data structure pointed to by pPreferencesWindow is deleted without the QSharedPointer's knowledge. When the QSharedPointer itself is later destroyed, it double-deletes the window, and you get the segfault.

Basically, as with all shared pointer implementations, either everybody plays, or nobody does. Since the Qt internals will never know you're using a smart pointer to manage the window, you can't use one. This is a blessing in disguise, however; it means that Qt itself takes possession of the pointer and agrees to manage it for you, so you don't need a smart pointer after all!

OTHER TIPS

I am not an expert with Qt but my first thoughts would be that QMainWindow deletes itself upon destruction and the QSharedPointer object will also delete the object when it's destroyed (i.e. the object is deleted twice). If this is true you don't need to use the QSharedPointer at all.

EDIT: It looks like the QtWidget Qt::WA_DeleteOnClose flag will cause the behaviour I have described.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top