I am using Qt 5.7 with C++ on Visual Studio Community 2015. What I know about Qt's resource control is that, when you kill a parent, you don't need to bother destroying the pointers child to that parent object. However, when I tried, I did not get results pointing to that direction, and I can't see why.
I run below code to get a reference point. Please note the code block commented out:
#include <QtWidgets/QApplication>
#include <QWidget>
#include <QPushButton>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget* w0 = new QWidget;
/*
QWidget* w1 = new QWidget;
w1->setWindowTitle("Window 1");
for(size_t i = 0; i < 1000; i++) {
QPushButton* pb = new QPushButton(w1);
}
w1->show();
*/
w0->show();
return a.exec();
}
With this code running, VS says the process memory is 4 MB.
And then I run below code to use more memory. Same code without the comment block:
#include <QtWidgets/QApplication>
#include <QWidget>
#include <QPushButton>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget* w0 = new QWidget;
QWidget* w1 = new QWidget;
w1->setWindowTitle("Window 1");
for(size_t i = 0; i < 1000; i++) {
QPushButton* pb = new QPushButton(w1);
}
w1->show();
w0->show();
return a.exec();
}
This time it used 9 MB of memory.
So far so good. Now what I would expect at this point is that, when I destroy w1, it should return the resources used by its child objects (push buttons) and I should see a decrease in the memory used. But it does not happen. I kill w1 and w0 is still running so I can still observe the memory usage, w0 is not a parent of w1, all push buttons are child to w1, yet the memory isn't returned. What am I doing/understanding wrong?
Update: In the above examples I just close (click the X up there) the window pointed to by w1, I think it would delete the pointer w1 too but to test it I have run the below code, and that code uses 6 MB of memory. So apparently 3 MB is returned after adding
delete w1;
New code below:
#include <QtWidgets/QApplication>
#include <QWidget>
#include <QPushButton>
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
QWidget* w0 = new QWidget;
QWidget* w1 = new QWidget;
w1->setWindowTitle("Window 1");
for(size_t i = 0; i < 1000; i++) {
QPushButton* pb = new QPushButton(w1);
}
w1->show();
w0->show();
delete w1;
return a.exec();
}
but there is still a 2 MB leak. Two questions at this point:
1. Why do I have to explicitly delete w1? Why is closing the window not enough? 2. Why is there still a leak even after I explicitly delete w1?