Why can't we create an object in Qt without a new keyword (i.e., on the stack)?

Why can't we create an object in QT without the new keyword? Usually we create a pointer to an object, for example:

 QLabel *ql=new QLabel(); ql->show() 

But I want to create an object like this:

 QLabel ql=QLabel(); ql.show() 

Is it possible?

+4
source share
5 answers

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(); } 
+19
source

Edit

 QLabel ql=QLabel(); 

to

 QLabel ql; 

and read some book in C ++.

+14
source

You can create Qt objects from the stack (without new ones), but these objects are automatically deleted when they go beyond. For instance:

 void doSomething() { QLabel ql; ql.show() } // scope ends, ql is deleted 

And that, how C ++ works, this is not a specific feature of Qt.

+3
source
 QLabel ql; 

creates a QLabel on the stack. Please note that he just lives until the current volume disappears.

+2
source

Such a code:

 QLabel ql=QLabel(); ql.show() 

will not compile since QLabel inherits from QObject. And you cannot make a copy of QObject because its constructor and assignment operators are disabled: http://doc.trolltech.com/4.6/qobject.html#no-copy-constructor

However

 QLabel ql; 

will work.

0
source

All Articles