9

I have set the WA_DeleteOnClose widget attribute in a MainWindow.

setAttribute(Qt::WA_DeleteOnClose);

However, whenever I close that main window, I get a segfault in its destructor, which only has delete ui;

In a nutshell, created a Qt4 GUI Application in Creator, added the setAttribute(Qt::WA_DeleteOnClose); to constructor, program now crashes on exit.

Jake Petroules
  • 23,472
  • 35
  • 144
  • 225

2 Answers2

13

Are you getting a segfault in its destructor the first time, or the second time? Remember that your main window destructor should run only once. That is to say that it should run either because of a stack unwind, or because of WA_DeleteOnClose, not both.

IIRC, Creator will put the main window on the stack of main(). Therefore, when main() returns the main window is destroyed.

MSalters
  • 173,980
  • 10
  • 155
  • 350
  • 5
    It turns out I accidentally declared my `MainWindow` class on the stack instead of the heap in `main()`. Your answer led me to realize such; thanks. :) – Jake Petroules Jul 01 '10 at 19:12
  • @JakePetroules `MainWindow` should normally be an automatic variable ("on the stack"), the issue was that you then shouldn't let Qt attempt to delete it. The C++ compiler will do it for you. There is this widespread misconception that all Qt objects must be explicitly allocated on the heap. In many cases that's just extra and unnecessary work: the C++ language has a well defined concept of scope and its relation to object lifetime. Before you do anything else, just leverage that and all will be well :) – Kuba hasn't forgotten Monica Oct 09 '19 at 14:21
  • Answering your question : it seems the crash happens in the **first** time the destructor is called. – LRDPRDX Nov 07 '21 at 13:41
  • @LRDPRDX: Compilers have advanced a bit over time. In particular, optimizers are shuffling around code a bit more than they used to. You probably want to verify the observation in a non-optimized build. The segfault is a result of Undefined Behavior, and the presence of Undefined Behavior tends to break optimizers., making the resulting crash hard to debug. – MSalters Nov 08 '21 at 13:23
  • @MSalters, irrelevant to your comment, but anyway see [my](https://stackoverflow.com/questions/69873560/double-free-or-corruption-out-error-on-a-stack-qdialog-with-the-wa-deleteon/69884726#69884726) post. – LRDPRDX Nov 08 '21 at 14:04
0

this link gives a good suggestion on solution.

Me I think the best is to define as QPointer to point to the obj and test NULL each time using it, so when the UI obj get destroyed, the pointer set to NULL directly. "QPointer provides guarded pointers for QObjects. You can use it to hold a reference to your dialog and when the dialog is deleted the pointer will be set to NULL automatically."

vivi
  • 334
  • 2
  • 13