PDA

View Full Version : Qt and C++ dynamic memory handling...



giowck
18th November 2009, 12:44
Hi guys,

i don't know what i missed, but can anyone explain me why all members of a QT class should be allocated on heap: i.e. QLabel *x = new QLabel

Why not on the stack? I know that everything you allocate on the heap, doesn't get destroyed until you call explicit the delete command...

Second, I know Qt deletes all child objects of a class, so i don't have to define the destructor, right?

Thanks :rolleyes:

scascio
18th November 2009, 13:48
In fact, calling the destructor (declared as virtual) of a QObject calls the destructor for all children.

So you allocate an object, add it as a child, and let the parent delete it for you, cause it owns it now.

But the destructor always need to be defined since it will be executed at object hierarchy destruction or explicitly delete call.

squidge
18th November 2009, 14:15
If you put them on the stack its far too easy for the ownership to be wrong and then you'll have all sorts of memory problems.

Normally, the parent deletes the object, so it needs to be allocated somewhere that will not attempt to delete it directly.

giowck
18th November 2009, 16:39
If you put them on the stack its far too easy for the ownership to be wrong and then you'll have all sorts of memory problems.

thanks both for the answers...

But i didn't understand what you mean with memory problems, what kind of problems? Any link/reference to this? I don't know this issue...

axeljaeger
18th November 2009, 16:48
Hi guys,
Why not on the stack? I know that everything you allocate on the heap, doesn't get destroyed until you call explicit the delete command...
Right. Thats the reason why you should always pass proper parents to your objects. Usually you create the root object in the main-method on the stack.



Second, I know Qt deletes all child objects of a class, so i don't have to define the destructor, right?
Wrong. Your destructor should release all resources you allocated yourself and that get not freed by Qt. It depends on your resources whether you need a destructor not on the fact that you are using Qt.

squidge
18th November 2009, 19:09
But i didn't understand what you mean with memory problems, what kind of problems? Any link/reference to this? I don't know this issue...
Well, if you transfer the ownership of an object to another object (eg. using QLayout::addItem), then it's that objects responsibility to delete it. If you delete it too by for example, going out of scope, you have a double free error, which may corrupt the free list, dereference a null pointer, or whatever.

giowck
18th November 2009, 19:50
ok
i looked on QObject docs and i solved my doubts! Thank you guys :D