PDA

View Full Version : Use of "delete"



Voldemort
2nd May 2007, 17:10
When I use things like:

file.h

QLabel *lblUserName;file.cpp

lblUserName = new QLabel(tr("Mailadres:"));Do I have to do this in the .cpp file (e.g. in the destructor):


delete lblUserName;Or isn't this needed when using Qt/Qt functions/Qt classes?

jpn
2nd May 2007, 17:14
Qt doesn't offer any magical all-covering garbage collection but a QObject deletes its children. For more information see:

Object Trees and Object Ownership (http://doc.trolltech.com/4.2/objecttrees.html)
QObject::~QObject() (http://doc.trolltech.com/4.2/qobject.html#dtor.QObject)

Voldemort
2nd May 2007, 17:25
1) I use 2 classes, these are 2 Widgets (inheritance), there are all Qt classes (like QAction, QPushButton, ...) in the functions, will they be delete automatically?

2) But what when I don't inheritance QObject or QWidget between an other class, will I have to delete all the others (like QAction, QPushButton)?

marcel
2nd May 2007, 18:13
1. If you create your classes with a parent that is not created by you explicitly, but by qt ( a main window, etc ), then your objs will be deleted automatically by their parent.
But if your objs are parentless, besides the fact that layouts and other things won't work properly, you'll have to delete them manually.

2. Manually, of course ( unless you have some object manager that takes care of them - disposes them as soon as no none uses them anymore ).

Regards

Voldemort
2nd May 2007, 21:45
1) So you mean when my class does not inheritance QObject or QWidget I have to delete them manually?

2) Can I delete all objects (parent or parentless) without problems (QObject complaining?)? Then I won't make any mistakes :).

marcel
2nd May 2007, 21:48
1. Yes. Is that so hard to do? Isn't c/c++ all about this? This is a great thing! More control, more flexibility... :). Of course, you can choose not to delete any objects :), but then everyone who uses your app will need a lot of memory.

2. Yes, you can delete them , but be sure to make them NULL right after you delete them.

Regards

Voldemort
3rd May 2007, 20:24
I'll only use delete when the class doesn't inheritance QWidget or QObject. Then everything should be ok.

@marcel: That's the reason why I program in C++, I like the control an flexibility and C++ is one of the fastest languages.

marcel
3rd May 2007, 20:31
Very well then :)

Regards