Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QMap/QHash operator[] returned reference validity

I was wondering for how long the reference to a value inside a Qt container, especially a QHash or a QMap is valid. By valid I mean if it is guaranteed to still point to the correct location inside the map/hash after inserting or removing other elements.

Let's the following code:

QHash<char,int> dict; // or QMap<char,int> dict;
dict.insert('a', 1);
int& val(dict['a']);

dict.insert('b', 2);

val = 3;             // < will this work or lead to a segfault

Will setting the value at the last line correctly update the value associated with a to 3 or will it lead to a segfault or will it be undefined (so work sometimes, segfault other times, depending on whether the data structure had to be reorganized internally, like resizing of the hash-table array). Is the behavior the same for QMap and QHash, or will one work and the other not?

like image 615
Janick Bernet Avatar asked Oct 30 '11 19:10

Janick Bernet


2 Answers

This is fully covered in the documentation — you must have missed it!

Iterators of both types are invalidated when the data in the container is modified or detached from implicitly shared copies due to a call to a non-const member function.

So, although I would expect iterators/references to remain valid in practice in the scenario you described above, you shall not rely on this. Using them in this way shall invoke Undefined Behaviour.

This holds for QHashIterator and QMutableHashIterator, as well as bare references. Beware of non-authoritative references claiming the opposite, relying on implementation details that may change at any time.

like image 101
Lightness Races in Orbit Avatar answered Oct 19 '22 14:10

Lightness Races in Orbit


There is nothing wrong with using references at QMap/QHash elements unless you delete the node you are referencing to. The elements of qt containers do not get reallocated every time a new elements is inserted. However I cannot see any good reason for using references to container elements.

For more details check this excellent article about qt containers internal implementation

like image 37
pnezis Avatar answered Oct 19 '22 15:10

pnezis