Ive been programming Qt for a while now and I am wondering what the difference is between these two cases:
case1:
header:
QPushButton * button;
source file:
button = new QPushButton(this);
button->setText("Button");
button->resize(100,100);
and
case2:
header:
QPushButton button;
source:
button.setParent(this);
button.setText("Button");
button.resize(100,100);
Both produce a button, but when should I use the former and when the latter case? And what is the difference between the two?
The difference between the first and second case is that when you use pointers and the new
statement to allocate the button, the memory for the button is allocated in the free store (heap). In the second statement the memory is allocated on the stack.
There are two reasons why you would rather allocate memory in the free store than the stack.
bad_alloc
exception is thrown.{...}
) that allocated the memory. When memory is allocated in the free store, you as the programmer have full control of the time that the memory remains valid (although carelessness can cause memory leaks)In your case, if the button just needs to exist for the duration of the calling function, you will probably be ok allocating the button on the stack; if the button needs to be valid for much longer stick to the free store
Qt memory management works with hierarchies of objects, when parent object deletes child objects automatically on destroying. This is why Qt programs always use pointers in similar cases.
Memory Management with Qt:
Qt maintains hierarchies of objects. For widgets (visible elements) these hierarchies represent the stacking order of the widgets themselves, for non-widgets they merely express "ownership" of objects. Qt deletes child objects together with their parent object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With