Is there a right or wrong for ownership in Qt

Viewed 94

I would like to write "modern C++" Qt applications, meaning with as much RAII as possible. Therefore I ask myself if it is safe to use automatic allocation when possible like this:

#include <QApplication>
#include <QtWidgets>
int main(int argc, char **argv) {
    QApplication app{argc, argv};
    QWidget window{};
    window.setWindowTitle("Der eine Knopf");
    QPushButton button{"Ende"};
    QObject::connect( &button, SIGNAL(clicked()), &app, SLOT(quit()));
    QVBoxLayout layout{};
    layout.addWidget(&button);
    window.setLayout(&layout);
    window.show();
    return app.exec();
}

Whereas the original tutorial code had a lot of pointers and heap:

#include <QApplication>
#include <QtWidgets>

int main(int argc, char **argv) {
  QApplication app{argc, argv};
  QWidget window{};
  window.setWindowTitle("Hallo Qt");
  QPushButton button = new QPushButton("Ende");
  QObject::connect( button, SIGNAL(clicked()),
      &app, SLOT(quit()));
  QVBoxLayout *layout = new QVBoxLayout;
  layout->addWidget(button);
  window.setLayout(layout);
  window.show();
  return app.exec();
}

I am aware of Qt's ownership concept of QObjects in general. So I assume the second example is correct. I assume that setLayout and addWidget also change the ownership and thus no explicit delete is needed for me as a client.

And assuming that I wonder -- why does my first example work then? If those methods acquire ownership, will they not delete their newly acquired children in the end? If they do, will my program not crash because the objects are removed twice? (The program does not crash, I would have mentioned that. But that could be by accident, right?)

I am now so much confused who owns whom and how does it work that I do not know how it could. The one rule I heard was "Qt will take care of that" -- but "of what"? And of what not?

Well, obviously I am new to Qt and what I would like is some insights into the QObjects constructor and destructor counts. Or messages for each construction and/or destruction. Is there such a facility in Qt?

1 Answers
Related