tags:

views:

220

answers:

2

Hi, Do I have to delete objects from the heap in the example below? And if yes, how?

#include <QApplication>
#include <QTreeView>
#include <QListView>
#include <QTableView>
#include <QSplitter>

int main(int argc, char* argv[])
{
    QApplication app(argc,argv);
    QTreeView* tree = new QTreeView;
    QListView* list = new QListView;
    QTableView* table = new QTableView;
    QSplitter* splitter = new QSplitter;
    splitter->addWidget(tree);
    splitter->addWidget(list);
    splitter->addWidget(table);
    splitter->show();
//    delete splitter; WHEN TRYING TO DELETE I'M GETTING INFO THAT app  EXITED
//    delete table;    WITH CODE -1073741819
//    delete list;
//    delete tree;
    return app.exec();
}

Thank you for any help.

+5  A: 

Just allocate splitter on the stack. Then tree, list and table become children of splitter which takes ownership. When splitter gets deleted, all the children are deleted.

From Widgets Tutorial - Child Widgets:

The button is now a child of the window and will be deleted when the window is destroyed. Note that hiding or closing the window does not automatically destroy it. It will be destroyed when the example exits.

See also Object Trees and Object Ownership.

Gregory Pakosz
Dzięki Grzesiek.
There is nothing we can do
But do I have to delete splitter object? Or shall I place it on the stack?
There is nothing we can do
Ah yes, well I would put the `splitter` on the stack
Gregory Pakosz
Yes, either delete it or place it on the stack.
Job
A: 

The way Gregory pointed you out is the best way to achieve what you want, but there's also another one:

int main(int argc, char* argv[])
{
    QApplication app(argc,argv);
    QTreeView* tree = new QTreeView;
    QListView* list = new QListView;
    QTableView* table = new QTableView;
    QSplitter* splitter = new QSplitter;
    splitter->addWidget(tree);
    splitter->addWidget(list);
    splitter->addWidget(table);
    splitter->show();
//    delete splitter; WHEN TRYING TO DELETE I'M GETTING INFO THAT app  EXITED
//    delete table;    WITH CODE -1073741819
//    delete list;
//    delete tree;

    int retval = app.exec();

    delete splitter;
    delete tree;
    delete list;
    delete table;

    return retval;
}

The reason why deletes are after is becouse app.exec() starts event loop, so your code deleted widgets before application event loop stated and this code deletes them when main event loop quits

Kamil Klimek
Tree, list and table will be automatically deleted because they are children of `splitter`. He must only delete the splitter.
laura
Or at least change the order of deletion.
Debilski