QMap / QHash [] operator returned referential validity

I was wondering how long the value refers to inside the Qt container, especially QHash or QMap . By valid, I mean that if you insert or delete other elements, you should still indicate the correct location inside the map / hash.

Let 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 the value on the last line correctly update the value associated with a to 3 , or it will result in segfault or it will be undefined (so sometimes run segfault at a different time, depending on whether the data structure should have been reorganized internally e.g. resizing a hash table array). Is the behavior the same for QMap and QHash , or does one work and the other not?

+6
source share
2 answers

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

Both types of iterators are invalid when the data in the container is modified or separated from implicitly shared copies due to a call to the non-const member function.

So, although I expected the iterators / links to remain valid in practice in the scenario described above, you should not rely on this. Using them in this way calls Undefined Behavior.

This is done for QHashIterator and QMutableHashIterator , as well as for links. Beware of unauthorized references, arguing the opposite, relying on implementation details that may change at any time.

+3
source

There is nothing wrong with using links in QMap / QHash elements unless you delete the node you are referencing. Qt container elements are not redistributed each time new elements are inserted. However, I see no good reason to use container element references.

Read more about this great article on qt 's internal container implementation.

+1
source

Source: https://habr.com/ru/post/900386/


All Articles