From this post, I can conclude that there're 2 main ways (there may be other ways, of course) of declaring a new widget in Qt:
- Not using
new
keyword:
QLabel lb;
lb.setText("a");
- Using
new
keyword:
QLabel *lb = new QLabel;
lb->setText("a");
So, in some of my tutorials, I've seen the instructor used the 2nd way, without using delete
afterward. From what I have read from a lot of articles (for instance this), when using new
we must always use delete
after that, to avoid memory leak.
But when reading other articles, for example this article, they mentioned that:
Only after your program terminates is the operating system able to clean up and “reclaim” all leaked memory.
In my program, sometimes I did use delete
when I want to completely vaporize something off the table:
QFormLayout *destroyAffineForm = inputFieldAffineBox->findChild<QFormLayout*>("inputFieldFormBoxAffine", Qt::FindChildrenRecursively);
while (destroyAffineForm->count() > 0 && (child = destroyAffineForm->takeAt(0)) != nullptr)
{
delete child->widget(); // delete the widget
delete child; // delete the layout item
}
delete destroyAffineForm;
But there're often a lot of widget that stays in place from the moment the program started, until it ended (without me calling delete
at the end), for example a QLabel
holding some header text.
So... all in all, will those variables (that persists through the process until the application is closed) create memory leaks and I have to insert a bunch of delete
statement to released them, or is the OS eventually going to handle it? (I know that maybe this is a duplicated question, but I'm getting lots of mixed statements here)
P.S: Some info about my machine
- Operating on Windows 10, 64-bit
- Qt Creator 4.14.2
- Qt 5.15.2 (MSVC 2019, 64 bit)