PDA

View Full Version : Behaviour of hash when key is QPointer<QObject*>



pkj
22nd September 2011, 14:29
I intend to use QPointer for pointer of my derived class from QObject as a key in QHash. According to QPointer documentation, the QPointer is made 0 after the object is deleted. If I use this QPointer in QHash, will the key be also made to 0? Or QHash makes the key by copying the int value of pointer, hence I will still be having the address of dangling pointer in my QHash?
If somehow the key is made to zero, if multiple objects are deleted, will I end up with a Qhash of multiple entries for the same key?
so somewhere in class.h

QHash<QPointer<MyObject>, SomeObject*> hashSomeObject
somewhere in class.cpp as a global function

uint qHash(const QPointer<MyObject>&ptr{
return qHash(ptr.operator()->());
}
somewhere in class.cpp


hashSomeObject.insert(myObject1, new SomeObject());
hashSomeObject.insert(myObject2, new SomeObject());
hashSomeObject.insert(myObject3, new SomeObject());
delete myObject1;
delete myObject2;
delete myObject3;

so what is hash now for the keys? Will the keys be made 0? Suppose I have a QList of QPointers, will they be carrying dangling addresses?

Zweistein
22nd September 2011, 15:47
Since your qHash Funktion returns an "uint" copy, i think the hash holds its old adresses. you can test it:


QHashIterator<QPointer<MyObject>, SomeObject*> i(hash);
while (i.hasNext()) {
i.next();
cout << i.key() << ": " << i.value() << endl;
}

pkj
23rd September 2011, 06:50
I think it's a bad idea to have a QPointer in a hash as a key. Might be ok as a value, but definitely not as a key. The global qHash function caused immense pain in linking and it doesn't even have the qpointer facilities :(