PDA

View Full Version : question about garbage collection



Dumbledore
18th December 2007, 19:44
When you reimplement a class and allocate memory on the heap then delete the class with deleteLater() or whatever, do you need to create your own destructor for that class to free the allocated memory?

links for recommended reading is appreciated!

marcel
18th December 2007, 19:50
If your reimplementation adds additional members which you allocate on the heap then yes, you need to delete them in the destructor. Otherwise, all the memory gets freed when the object is deleted in the event loop.

Recommended reading: http://www.qtcentre.org/forum/f-general-discussion-10/t-c-best-tutorial-training-10774.html#post57155.

Dumbledore
18th December 2007, 21:20
haha thinking in C++ is a little less targeted than what I was expecting. But I suppose the message is that Qt doesn't add any garbage collection functionality? I only ask because in the examples I've seen there is never any reimplementation of the destructors to delete the memory allocated to the new members...

For instance maybe something like this:



#ifndef DIALOG_H
#define DIALOG_H

#include <QDialog>
#include "fortuneserver.h"

class QLabel;
class QPushButton;

class Dialog : public QDialog
{
Q_OBJECT

public:
Dialog(QWidget *parent = 0);

private:
QLabel *statusLabel;
QPushButton *quitButton;
FortuneServer server;
};

#endif


I don't see a specialized destructor and I'm just curious when I would need the destructor.

marcel
18th December 2007, 21:26
That is because statusLabel and quitButton are created with this as parent, therefore they will be deleted when this gets destroyed. A QObject always deletes all its children.

I was talking about about non-QObject members allocated on the heap. They have to be deleted manually.

rickbsgu
18th December 2007, 22:08
haha thinking in C++ is a little less targeted than what I was expecting. But I suppose the message is that Qt doesn't add any garbage collection functionality?
If you're thinking like Java or C# or one of the other interpreted/VM-based languages, the answer is, "No, there is no garbage-collector." (The exception is something MS calls 'managed C++' in their .NET/cli framework - certainly not a standard C++.)

Memory is allocated and freed explicitly. Some systems (like Qt) help you out a bit, like the example Marcel gives. You need to know that - not freeing a pointer means memory leaks, freeing an already freed pointer will cause much grief.

rickb