Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

qt

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

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

But I want to create an object like this:

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

Is it possible?

like image 842
maysam Avatar asked Nov 27 '22 00:11

maysam


2 Answers

The thing is that the Qt controls (labels, buttons) are in a hierarchy (buttons belong to forms, for example). And the way Qt is implemented requires that when an object is destroyed, all objects that belong to it are destroyed as well.

If you place objects on a stack (that's how "create without new keyword" is really called), they will be destroyed automatically. That's the property of C++, and it holds for all programs. Here's how the things would 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's already dead!
  // Program crashes!

Such stack allocation would mean that when you destroy the object the label belongs to, the label might already have been destroyed. It will make your program crash.

Actually, you can sometimes create objects on stack. In the main function, you may allocate on stack your "main control" (usually it's the main window). The thing is that this object won't be destroyed during the program execution, so it can safely be on stack until main exits--i.e. the program terminates. Here's a quote from 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();
 }
like image 53
P Shved Avatar answered Dec 19 '22 17:12

P Shved


Change

QLabel ql=QLabel();

to

QLabel ql;

and read some C++ book.

like image 36
Wildcat Avatar answered Dec 19 '22 18:12

Wildcat