The fact is that Qt controls (labels, buttons) are in a hierarchy (for example, buttons belong to forms). And the Qt implementation method requires that when an object is destroyed, all objects belonging to it are also destroyed.
If you push objects onto the stack (what is really called "create without new keyword"), they will be destroyed automatically. This is a C ++ property, and it runs for all programs. Here, how everything will work if you allocated your label on the stack.
{ QLabel ql = QLabel(some_form); ql.show() } // scope ends, ql is deleted delete some_form; // ql will be deleted here as well // but it already dead! // Program crashes!
Such a stack distribution would mean that when you destroy the object to which the label belongs, the label may have already been destroyed. This will cause your program to crash.
Actually, sometimes you can create objects on the stack. In the main function, you can push your "main control" onto the stack (usually this is the main window). The fact is that this object will not be destroyed during the execution of the program, so it can safely be on the stack until the main outputs - i.e. the program ends. Here is a quote from a Qt tutorial :
#include <QApplication> #include <QPushButton> #include <QTranslator> int main(int argc, char *argv[]) { QApplication app(argc, argv); QTranslator translator; translator.load("hellotr_la"); app.installTranslator(&translator); QPushButton hello(QPushButton::tr("Hello world!")); hello.resize(100, 30); hello.show(); return app.exec(); }
source share