user15202364
user15202364

Reputation:

Using 'new' to declare variables without using delete afterward in Qt

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

Upvotes: 1

Views: 490

Answers (1)

JarMan
JarMan

Reputation: 8277

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

Upvotes: 3

Related Questions