PDA

View Full Version : main.cpp and creating an instance of QMainWindow



ravas
23rd October 2015, 10:18
I've noticed that all the examples in the Qt documentation
create the toplevel instance of QMainWindow using the stack.
The project I'm working on creates it (in the main function) using the heap.
Regarding the missing call to delete, does it matter in this case?
Is everything still properly deleted because the program terminates?

weiweiqiao
23rd October 2015, 11:32
you mean that you create a instance of QMainWindow by "new ****"?
i thought you'd better delete each pointer for freeing res.

yeye_olive
23rd October 2015, 13:33
Is everything still properly deleted because the program terminates?
No, the destructor is not called. The OS typically frees all the resources it tracks, such as memory and open file descriptors, but that's all. If, for instance, the destructor of your main window saves some data to a configuration file, you need the destructor to be called, e.g. with delete.

More generally, it is good practice to explicitly release the resources you allocate. If you want to allocate the main window on the heap and still have it automatically deleted at the end of the enclosing scope, consider wrapping the pointer in a smart pointer, such as std::unique_ptr.

ravas
23rd October 2015, 20:00
Thanks guys.

ravas
24th October 2015, 01:07
It turns out the project was using

setAttribute(Qt::WA_DeleteOnClose);

It seems like this feature is intended for windows other than the top level QMainWindow.

anda_skoa
24th October 2015, 09:40
It seems like this feature is intended for windows other than the top level QMainWindow.
It can be used for any widget that is not allocated on the stack.

Usually used for widgets that are windows, e.g. QMainWindow, QDialog based windows, or other widgets without parent.

Cheers,
_

Hossein
24th October 2015, 18:22
No, the destructor is not called. The OS typically frees all the resources it tracks, such as memory and open file descriptors, but that's all. If, for instance, the destructor of your main window saves some data to a configuration file, you need the destructor to be called, e.g. with delete.

More generally, it is good practice to explicitly release the resources you allocate. If you want to allocate the main window on the heap and still have it automatically deleted at the end of the enclosing scope, consider wrapping the pointer in a smart pointer, such as std::unique_ptr.

If the OS, frees it, then why do we have memory leaks ? why do we even care to free the memory in first place?
(Is it that OS will not reclaim memory as long as the app is running, and thus if the app doesn't free it, while working, it may very soon consume all memory because of that leakage!?)

anda_skoa
24th October 2015, 19:29
If the OS, frees it, then why do we have memory leaks ?
As yeye_olive already wrote, memory is not the problem.

Cheers,
_