Why does Qt require allocating children on the heap?

class MyWidget : public QWidget { public: MyWidget( QWidget *parent=0, const char *name=0 ); }; MyWidget::MyWidget( QWidget *parent, const char *name ) : QWidget( parent, name ) { QPushButton *quit = new QPushButton( "Quit", this, "quit" ); quit->setGeometry( 62, 40, 75, 30 ); quit->setFont( QFont( "Times", 18, QFont::Bold ) ); } 

In the above code, quit is highlighted in Heap, and this is necessary because it is a child of MyWidget

Why does Qt require allocating children on the heap?

+6
qt
source share
4 answers

I think the idea here is that Qt has its own internal reference count for most objects, and if you pass them, uses copy-on-write, etc.

Could you be more specific in your question?

0
source share

In your quit example, there is no need to allocate a bunch.

This code compiles and does a fine:

 struct MyWidget : QWidget { QPushButton quit; MyWidget() { quit.setGeometry( 62, 40, 75, 30 ); quit.setFont( QFont( "Times", 18, QFont::Bold ) ); } }; 
+5
source share

If I understand what you are asking correctly, I think it basically comes down to traditions and examples with a few heading dependencies.

An alternative, of course, is to declare quit as a member variable of MyWidget . If you do this, you will need to include the header file for QPushButton , where MyWidget declared, and not in the implementation file. The example you used also uses the parent relationship QObject to track the memory for the button and delete it when it is destroyed, so it does not need to be specified as a member in the class.

I'm sure you could change the stack distribution if you want.

+2
source share

What other options are there? From the stack? How does Qt know when to allocate from the stack and when from the heap? Things allocated from the stack will disappear as soon as the current function returns, so the lifetime of the object can be much shorter than the time of use. Imagine adding node to a tree. node will be used long after the current function returns. This will result in access to random memory, segmentation errors, kernel dumps, etc.

-one
source share

All Articles