1

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.

demonplus
  • 5,613
  • 12
  • 49
  • 68
WolfgangP
  • 3,195
  • 27
  • 37

2 Answers2

5

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 Coates
  • 8,520
  • 3
  • 31
  • 37
1

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
  • 76,898
  • 55
  • 205
  • 325