Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do I use pointers in Qt?

Tags:

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?

like image 563
Frank Avatar asked Sep 11 '13 15:09

Frank


2 Answers

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.

  1. The stack is of limited size and if you blow your stack budget your program will crash with a stack overflow. One can allocate much more memory in the free store and if a memory allocation fails, all that normally happens is that a bad_alloc exception is thrown.
  2. Allocation on the stack is strictly last in first out (LIFO) which means that your button cannot exist for longer than the code block (whats between the {...} ) 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

like image 93
doron Avatar answered Sep 20 '22 14:09

doron


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.

like image 41
Alex F Avatar answered Sep 21 '22 14:09

Alex F