unordered_map 调整大小后指向元素值的指针是否有效?

unordered_map pointer to element's value valid after resize?

如果我有 unordered_map<key, someNiceObject>

(注意someNiceObject不是指针)

我有一个 API 插入一个新元素,然后 returns 一个指向 someNiceObject 现在在地图中的指针。

如果我在地图中执行更多插入操作,容量可能会发生变化。如果发生这种情况,指针是否仍然有效?

我试过阅读 Basic questions: Pointers to objects in unordered_maps (C++), http://eel.is/c++draft/unord.req#9

并且找不到必要的信息

谢谢大家

编辑:指针似乎是有效的(https://www.thecodingforums.com/threads/do-insert-erase-invalidate-pointers-to-elements-values-of-std-unordered_map.961062/)

虽然会感谢这里有人对 SO 的第二次确认。

根据cppreference

If rehashing occurs due to the insertion, all iterators are invalidated. Otherwise iterators are not affected. References are not invalidated.

这意味着指针也没有失效。这是可能的,因为 std::unordered_map 在概念上可以被认为是 std::vector<std::forward_list<std::pair<Key, Value>>>。由于 std::forward_list 与任何其他链表一样,分别分配每个元素,因此对列表的更改不会影响其元素的内存位置。

std::unordered map 的不寻常之处在于迭代器失效规则不适用于对元素的引用(不包括删除,但是当项目消失时你能做什么?)。容量变化并不重要。问题是当 unordered map 重新散列时。重新散列将使所有迭代器失效,但不会使引用失效。

来自 C++ 标准中 [unord.req] 的第 9 点(引用 n4618,因为这是我目前手头的),

The elements of an unordered associative container are organized into buckets. Keys with the same hash code appear in the same bucket. The number of buckets is automatically increased as elements are added to an unordered associative container, so that the average number of elements per bucket is kept below a bound. Rehashing invalidates iterators, changes ordering between elements, and changes which buckets elements appear in, but does not invalidate pointers or references to elements. For unordered_multiset and unordered_multimap, rehashing preserves the relative ordering of equivalent elements.

强调我的