PDA

View Full Version : QHash Clear



enricong
12th October 2011, 16:06
When I use QHash clear(), does this delete all children (and children of children in nested containers)?

Also, I have some QHash's (and other QT containers) which point to my own typedef structs. Will clear() delete those for me too?

I couldn't tell from reading the documentation.

stampede
12th October 2011, 18:23
clear() will not call operator delete on pointers stored in the QHash, if you ask about it. You need to release the memory allocated with operator new yourself.
If the structs are kept by value, then memory will be freed.

totem
12th October 2011, 18:40
Also, you can make use of the convenient qDeleteAll(), like:


qDeleteAll( m_hashMap ) ;

This will free memory for values stored in the container.
Note that this will not call clear() on the container.

enricong
12th October 2011, 20:59
ok, I see, if I have values stored by reference, it will just clear the pointers, but not free the memory of the objects they are pointing to.

Does this also apply to Qt containers? if I have nested Qt Containers, will it at least call clear in the nested container?

for example, if I have something like:
QHash<int, QList<int,float> testhash

will clear() call clear() for each QList "value"?

stampede
12th October 2011, 21:28
QHash<int, QList<int,float>
I don't really know how to interpret that, did you mean:

QHash<int, QList< QPair<int,float> > > hash;?
Anyway, with stack-allocated objects, hash.clear(); is enough, it will remove all the associated data from the memory.

enricong
12th October 2011, 21:42
oh sorry, I meant

QHash< int, QList<float> > hash;

but I think you answered my question, if I do hash.clear() all the QLists will be deleted.

But If I have something like



typedef struct customtype{
QList<float> list;
};

QHash< int, customtype > hash;

hash.clear() will not delete the structs

stampede
12th October 2011, 22:01
hash.clear() will not delete the structs
Of course it will, why do you think so ?
Try this code and see the output:


#include <QApplication>
#include <QDebug>

struct customtype{
QList<float> list;
~customtype(){
qDebug() << "deleting customtype..." << list.count();
}
};

int main(int argc, char *argv[])
{
QHash< int, customtype > hash;
hash[1].list.append(2);
hash[1].list.append(3);
hash[2].list.append(1);
qDebug() << "before clear()";
hash.clear();
qDebug() << "after clear()";
return 0;
}