QHash and memory
-
Hello,
I have the following defined in my header file.
QHash<int , Data*> *DataHash;
In my cpp constructor I have this:
DataHash = new(QHash <int, Data*>);
When i receive data I insert into the qhash by putting it in a new data and insert it into the qhash
data= new Data(a, b, c); DataHash->insert(number, data);
Every x seconds I need to search the qhash for old data and remove it.
QHash<int, Data *>::iterator it = DataHash->begin(); while (it != FlightDataHash->end()) { if(nowTime > t) { Data *tmp = DataHash->remove(it.value()->getTrackNumber()); //remove, erase or take? delete tmp; // it = FlightDataHash->erase(it); //Seg fault: QUESTION do i need something like this or is "delete tmp" enough to remove memory? }
My question is will the remove and the delete tmp be enough to ensure I don't have a memory leak from when i created the "data= new Data(a, b, c); "
Is using remove() the correct call or is take() or erase() better?Thank you very much
-
- Remove the data from the QHash:DataHasht.erase(it) (see example in https://doc.qt.io/qt-5/qhash-iterator.html)
- Delete data itself: delete tmp;
-
@taraj Please read carefully https://doc.qt.io/qt-5/qhash.html#erase , then you will know what you're doing wrong now!
-
@jsulm
"Removes the (key, value) pair associated with the iterator pos from the hash, and returns an iterator to the next item in the hash."
where does it remove the data to? How can I access the data to delete it from memory?FlightData *tmp = FlightDataHash->remove(it.value()->getTrackNumber()); delete tmp; it = FlightDataHash->erase(it); //This will seg fault
i'm back to the above, this is what i had in the original post?
-
@taraj said in QHash and memory:
FlightData *tmp = FlightDataHash->remove(it.value()->getTrackNumber());
Shouldn't it be
FlightData *tmp = it.value(); delete tmp; it = FlightDataHash->erase(it);
-
@jsulm said in QHash and memory:
@taraj said in QHash and memory:
FlightData *tmp = FlightDataHash->remove(it.value()->getTrackNumber());
Shouldn't it be
FlightData *tmp = it.value(); delete tmp; it = FlightDataHash->erase(it);
Just as I said:
delete
the data pointer before doing the iteratorerase()
.