tags:

views:

895

answers:

3

I'm using a rather complex QList in a derivation of QAbstractTableModel to store data:

class MyTableModel : public QAbstractTableModel {
     Q_OBJECT   
     QList<QHash<int, QHash<int, QVariant> *> *> m_data;
     /*...*/
};

MyTableModel::~TMusicTableModel() {
     /* Should I deallocate QList items? */
}

MyTableModel::setData(int row, int col, int type, QVariant value) {
    /* inserting a new data field */
    QHash<int, QHash<int, QVariant> *> *row_hash = new QHash<int, QHash<int, QVariant> *>();
    QHash<int, QVariant> *role_hash = new QHash<int, QVariant>();
    type_hash->insert(type, value);
    row_hash->insert(col, type_hash);
    m_data.insert(row, row_hash);
    return true;
}

I'm wondering if the QList and QHashes take care of the deallaction or if I should do it. The documentation is not very informative in this case.

cheers

A: 

I think the QList will handle the deallocation itself, if this doc quote is correct:

The internal array is deallocated by the destructor and by the assignment operator

At work we have a compiler option for VTK (Visualization Toolkit) called vtk_debug_leaks, which will report all of the class instances left in memory when a VTK program exits. There must be some equivalent memory leak debugger available that you could use to measure the same class instance leakage for Qt.

If you want to manage the memory yourself to be sure, it looks like you could get away with just iterating the QList and calling .clear() on the outer QHash items.

Chris Cameron
A: 

Like any other container class in practically any C++ library, destructing it also activates the destructor of the elements in it. this is true for a simple MyClass array[3], for STL vector<MyClass> and for QT's QList<MyClass> as well.
To make sure everything is destroyed you need to make sure that MyClass has a destructor that indeed deallocates all the resources. Having a QList of pointers does not follow this rule because pointers don't have destructors. instead you may want to use boost's shared_ptr or write your own smart pointer wrapper.

shoosh
+2  A: 

Because you're creating the sub items with "new", you do have to deallocate them yourself. See the qDeleteAll function for a quick way of doing so.

Is there a reason why you're using new to create these hashs? (Your code is obviously just a snippet, so the pointers could be used and passed around elsewhere.) Generally, it's much simpler to just construct them on the stack so that destruction happens automatically.

Parker
this seems to be the only answer that is concise and actually answers the question
Idan K
yes it is. Thanks!
Wolfgang Plaschg