Tuesday, December 29, 2009

Demonstrating Qt's Automatic Destructor

Mas Ariya Hidayat told me that Qt had automatic memory management / garbage collection features. It's one feature that made me more interested in Java, C#, Ruby, PHP, and Python, than C and C++.

In practice, this means that Qt objects are automatically deleted when its parent is deleted.

By "Qt object" I mean any object that inherits QObject.

From qt-interest discussion: Qt Class Destructor - No Need for Delete:
If the constructor for the class expects a QObject* parent parameter, and you pass it one, then you can expect that when the parent dies, the child will also die. If it does not expect such a parameter, or it expects one but you pass it 0, or do not pass it anything and thus it defaults to 0, then you will need to clean the object up yourself later with delete.

Demo-ing Automatic Destructor on Hello World App

Let's take my previous Hello World app and add a destructor.



HelloWorld::~HelloWorld() {
    printf("Bye bye...!\n");


and use the new operator to create HelloWorld object:

main.cpp :


    HelloWorld *helloWorld = new HelloWorld(&a);
    QObject::connect(helloWorld, SIGNAL( done() ), &a, SLOT( quit() ), Qt::QueuedConnection);
    QTimer::singleShot(0, helloWorld, SLOT( sayHello() ));


Run the application, and we get:

Starting /home/ceefour/Sandbox/helloworld-console/helloworld-console...
Starting up...
Hello World!
Bye bye...!
/home/ceefour/Sandbox/helloworld-console/helloworld-console exited with code 0

Works as advertised! The HelloWorld::~HelloWorld() destructor is called, and there's no need to delete the object explicitly.

The secret recipe is this particular line:

HelloWorld *helloWorld = new HelloWorld(&a);

It creates the HelloWorld object as a child of Qt application.

In effect, when Qt application object is destroyed, the HelloWorld object gets destroyed first.

If we change it to this:

HelloWorld *helloWorld = new HelloWorld;

The destructor won't be called automatically, and we have to call it ourselves.

I don't think it's technically an automatic memory management with garbage collection, but when used properly, it's very useful.

No comments:

Post a Comment

Be the first to comment!