QMap/QHash 运算符[]返回引用有效性
我想知道对 Qt 容器内的值的引用(尤其是 QHash
或 QMap
)的有效时间是多长。我所说的有效是指在插入或删除其他元素后是否保证它仍然指向映射/散列内的正确位置。
让我们编写以下代码:
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
正确设置最后一行的值会将与 a
关联的值更新为 3
还是会导致段错误或未定义(因此有时有效,有时会出现段错误,具体取决于数据结构是否必须在内部重新组织,例如调整哈希表数组的大小)。 QMap
和 QHash
的行为是否相同,或者一个有效而另一个无效?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 QMap/QHash 元素上使用引用没有任何问题,除非删除正在引用的节点。每次插入新元素时,qt 容器的元素不会重新分配。但是,我看不出使用对容器元素的引用有任何充分的理由。
有关更多详细信息,请查看这篇关于qt 容器内部实现的优秀文章
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
文档对此进行了全面介绍 - 您一定错过了!
因此,尽管我希望迭代器/引用在您上面描述的场景中实际上保持有效,但您不应依赖于此。 以这种方式使用它们将调用未定义的行为。
这适用于
QHashIterator
和QMutableHashIterator
以及裸引用。谨防那些声称相反的非权威参考文献,它们依赖于随时可能更改的实现细节。This is fully covered in the documentation — you must have missed it!
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
andQMutableHashIterator
, as well as bare references. Beware of non-authoritative references claiming the opposite, relying on implementation details that may change at any time.