Dynamic memory in QT

advertisements

I have noticed in QT 5 examples there is no delete call for new widgets allocated.

Does this mean in this example

using namespace std;

#include <QApplication>
#include <QMainWindow>
#include <QTabWidget>

//This is to be used in many files later until the code exits
short * AA = new short[1000000];

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    MyTabDialog w;
    w.show();

    delete[] AA;
    return app.exec();

}

the delete call is not needed or its place is wrong?

Thanks


If you really want to do this in your code snippet you should place delete after application event loop is finished:

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    MyTabDialog w;
    w.show();

    int result = app.exec();
    delete[] AA;
    return result;
}

But why do you allocate AA from the heap? You can just define it as following:

short AA[1000000];

And in Qt examples the widgets commonly created dynamically, for example:

QWidget* myWidget = new QWidget(this);

In example above this is pointer to another QObject instance which is now the parent for myWidget. Now myWidget instance will be automatically destroyed on deleting of it's parent widget and that's why we don't need to call delete explicitly for this instance.

Object trees and ownership reference here.