[Qt] memory management and implicit sharing

There are some points that we have to know when we program using Qt:

  • 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.
Only if you have Classes with QObjects, then child items will be deleted if the parent is deleted:

QObject *parent = new QObject; 
QWidget *child1 = new QWidget(parent); QPushButton *child2 = new QPushButton(parent); delete parent; // child1 and child2 will be deleted automatically!


Implicit sharing (IS)
The following example is about how implicit sharing works when test() returns QList object (on stack). This memory address of "a" is shared to "result" and "a" is not destroyed when method:test() is out of scope.
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QList> #include <QtGui> QList<QString> MainWindow::test() { QList<QString> a; // on stack QList<QString> b = QList<QString>(); // on stack QList<QString> *c = new QList<QString>(); // on heap for (int i = 0; i < 10; i++) { /* if we append a reference of QString, it will consume the memory of the QList Object based on the size of string */ a.append("a_helo:"); a.append(QString::number(i)); b.append("b_helo:"); b.append(QString::number(i)); c->append("c_helo:"); c->append(QString::number(i)); } qDebug() << a << " addres:" << &a; qDebug() << b << " addres:" << &b; qDebug() << *c << " addres:" << c; //delete &b; // we cannot manually free the memory of b or c on stack delete c; // OK return a; // Implicit Sharing } MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); /* The memory address of result is same with a object in test() because of implicit sharing */ QList<QString> result = test(); QList<QString> result2; qDebug() << result << " addres:" << &result; qDebug() << result2 << " addres:" << &result2; } MainWindow::~MainWindow() { delete ui; }


Popular posts from this blog

[Open vSwitch] How to get port statistics from interface in OVS

[Quagga] How to compile and install Quagga on Ubuntu 12.04

[JSON] How to use jansson lib to generate JSON data in C