David Mokon Bond
David Mokon Bond

Reputation: 1656

When to call the QApplication destructor

So I realize that in fact I really do not need to do what I am about to explain but I am very picky about making sure my programs cleans up everything before exiting so I still want to do it...

I have a QApplication that I connect a single shot timer to the quit slot on. (in the future imagine this quit is really going to be generated from the UI on a user click so this is just for debugging) I have noticed that at first I was just allocating the qApp in the main function on the stack. The problem is in doing some research it seems the exec function does NOT HAVE to return. This means the main function stack does not get cleaned up. (Or well at least not until the program exits and the system reclaims that memory...) So in valgrind I have some QCoreApplication::init() memory "issues". Once again more just me being picky then really affecting things...

Anyways so I decided to malloc the QApplication and then try to free it just before the program closes. I can do this for signals but how about on the quit signal? I'm tied into the aboutToQuit signal but I feel like that's not the right stage to blow away the qApp. So my question is, IS there a right place to delete the qApp and if yes where?

Upvotes: 2

Views: 839

Answers (1)

The problem is in doing some research it seems the exec function does NOT HAVE to return.

Well, yeah, it doesn't "have" to return if your process is crashing and burning anyway, i.e. if you've called - directly or indirectly - std::terminate(), ::abort(), ::exit(), etc. Those library functions are used to quickly terminate the process and your problems aren't limited to the QApplication instance. Every object on the call stack, in every thread, will be leaked, and some of those objects you have neither access to nor any control of - the runtime and the libraries create them - and there's nothing you can do about it. The case of non-returning exec() is an exception, not the normal way your program should be ending. In terms of "what to do when exec() doesn't return: nothing. It's too late by then.

Hence - don't throw uncaught exceptions, don't ::exit() nor ::abort(), and don't worry about it. In every well-behaved Qt program, QCoreApplication::exec() returns.

Upvotes: 2

Related Questions