QHash and pointer to members question
-
Hi everyone,
I have a question for you, which for some of you might be very simple, but I need to be sure.I have a QHash list with some members inside. Now I need to pass a pointers pointing to some of the members in the list, my question is what will happen if one or more of the members in the list are removed? Will the removal of one member re-shifts the members after it in the memory, resulting in pointer pointing to a wrong memory?
Todor
-
Hi,
Can you share a code sample that shows what you are trying to do ?
-
Modifying contents of a QHash invalidates (potentially) any pointers pointing into it as the memory needed to store the hash table could be reallocated for growth (or shrinking).
You can read more about it here. Every time iterator invalidation is mentioned you can assume it also applies to pointers into the container. It is generally not safe to keep pointers to elements in containers.
Few alternatives are storing pointers in the containers, using uuids and find instead of pointers or use of non-mutable size containers like
std::array<T>
, all depending on your particular use case and complexity requirements. -
I am not storing pointers in the QHash, I store a real genuine copy of the objects, but I pass pointers to different executable classes which can live 30 minutes or more, but during that time the QHash will be updated (new objects inserted or old one removed from the list). I have already developed a method to notify the related classes "to remove the pointer" of the used object in them upon removal of that object from the list, but my concern is for the other pointers that are still "alive" in the list, but the memory address have been changed due to the QHash reshuffle.
QHash<QString, CustomClassObject> Objects; CustomClassObject* obj = Objects["SECOND"]; SignalClass* signal = new SignalClass(obj); //This can live up to 30 minutes or more Objects.RemoveAll("FIRST");
will the obj still point to the correct real list object or I will have a memory corruption?
-
I can only repeat myself: "modifying contents of a QHash invalidates (potentially) any pointers pointing into it".
In short - no, the pointer will (most likely) not point to the correct memory location after that sequence.