c++qtqlistqhash

How to clean up a complex QList?


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.


Solution

  • 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.