Qt Memory Management

Objectives

  • Understand where and when Qt deletes objects
  • Know when a developer is responsible for providing code deleting allocated objects
  • Understand when heap and stack allocation are used in Qt

Memory Management

  • The ownership of all child QObjects is transferred to the parent.
    • Automatic deletion by the parent
    • Allocated from the heap (using new)
    • manual deletion is not necessary but it won't cause any problems.
  • All QObjects without a parent must be deleted manually.
  • Pay attention to ownership and responsibilities. Qt does not provide a garbage collection.

Creating Objects

  • Objects inheriting from QObject are allocated on the heap using new. If a parent object is assigned, it takes ownership of the newly created object - and eventually calls delete.
  • Objects not inheriting QObject are allocated on the stack.

Example 1: Correct way to create objects.

#include <QtGui>
 
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
 
    QLabel *label = new QLabel("Testing");
    QWidget window;
    label->setParent(&window);
    window.show();
 
    return app.exec();
}

Example 2: Wrong way. See what happens after you close the window.

#include <QtGui>
 
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
 
    QLabel label("Testing");
    QWidget window;
    label.setParent(&window);
    window.show();
 
    return app.exec();
}

Heap and Stack Allocation in Qt

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.