QMap/QHash 运算符[]返回引用有效性

发布于 2024-12-12 21:32:47 字数 545 浏览 3 评论 0原文

我想知道对 Qt 容器内的值的引用(尤其是 QHashQMap )的有效时间是多长。我所说的有效是指在插入或删除其他元素后是否保证它仍然指向映射/散列内的正确位置。

让我们编写以下代码:

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 还是会导致段错误或未定义(因此有时有效,有时会出现段错误,具体取决于数据结构是否必须在内部重新组织,例如调整哈希表数组的大小)。 QMapQHash 的行为是否相同,或者一个有效而另一个无效?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

青春有你 2024-12-19 21:32:48

在 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

允世 2024-12-19 21:32:47

文档对此进行了全面介绍 - 您一定错过了!

当容器中的数据被删除时,这两种类型的迭代器都会失效
由于调用而被修改或与隐式共享副本分离
非常量成员函数。

因此,尽管我希望迭代器/引用在您上面描述的场景中实际上保持有效,但您不应依赖于此。 以这种方式使用它们将调用未定义的行为。

这适用于QHashIteratorQMutableHashIterator以及裸引用。谨防那些声称相反的非权威参考文献,它们依赖于随时可能更改的实现细节。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文