[Development] Question about the lifetime of references taken from QHash
Giuseppe D'Angelo
giuseppe.dangelo at kdab.com
Thu Mar 11 12:36:02 CET 2021
Il 11/03/21 12:30, Jaroslaw Kobus ha scritto:
> Provided I have only one instance of my QHash (so, no detaches are being done), and the only API of the QHash I'm using is: insert(), remove(), contains() and operator[], how long I may rely on the reference to value returned by QHash::operator[]?
> E.g.:
>
> QHash<int, MyValue> hash;
> hash.insert(1, MyValue(...));
> hash.insert(2, MyValue(...));
>
> MyValue &val = hash[1];
> hash.remove(2);
>
> // May I rely that now my reference is still valid? Wondering, if any internal rehash on remove could copy internal data, so that it invalidates the reference obtained earlier.
>
> Assuming that I keep and use this reference only until I explicitly called hash.remove() for the key associated with my reference - may I assume that this reference will be valid?
The quick answer is: in Qt 5 `val` is still valid (modifications of the
container only affect iterators/references to the modified elements),
while in Qt 6 it's not (modifications of the container invalidates all
iterators and references).
So don't rely on that if you want to future-proof your code. (Or, if you
really want to rely on that, then switch to std::unordered_map).
HTH,
--
Giuseppe D'Angelo | giuseppe.dangelo at kdab.com | Senior Software Engineer
KDAB (France) S.A.S., a KDAB Group company
Tel. France +33 (0)4 90 84 08 53, http://www.kdab.com
KDAB - The Qt, C++ and OpenGL Experts
-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/pkcs7-signature
Size: 4329 bytes
Desc: Firma crittografica S/MIME
URL: <http://lists.qt-project.org/pipermail/development/attachments/20210311/9b646a60/attachment.bin>
More information about the Development
mailing list