0

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:

  1. Not using new keyword:
QLabel lb;
lb.setText("a");
  1. 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)

1 Answers1

2

All QObjects will delete their own child objects automatically. (See docs here.) QWidgets are QObjects. So as long as you establish a parent/child relationship, you do not need to manually delete your objects. To do that, simply pass a pointer to the parent object to the constructor:

QLabel *label1 = new QLabel;   // <<- NEED TO DELETE
QLabel *label2 = new QLabel(some_parent_obj);   // Will be deleted when some_parent_obj is deleted
JarMan
  • 7,589
  • 1
  • 10
  • 25
  • You may want to link to this: [https://doc.qt.io/qt-5/qobject.html#dtor.QObject](https://doc.qt.io/qt-5/qobject.html#dtor.QObject) – drescherjm Jun 01 '21 at 18:24
  • @drescherjm Good suggestion! – JarMan Jun 01 '21 at 18:25
  • This may seems like a trivial question, but, for widgets created within the `.ui` file in QtCreator (not created by code), their parent is already set, so there's no need to do anything, or vice versa? (Example pic : https://ibb.co/BtyRB3b) –  Jun 01 '21 at 23:11
  • 2
    I don't ever use that myself, but I can't imagine that you need to delete those objects that QtCreator makes for you. – JarMan Jun 02 '21 at 01:59