如果我有一个unordered_map<key, someNiceObject>
(注意someNiceObject
不是指针)
我有一个API,该API会插入一个新元素,然后现在在 map 中返回一个指向someNiceObject
的指针。
如果我进一步插入 map ,则容量可能会发生变化。如果发生这种情况,指针是否仍然有效?
我尝试阅读
Basic questions: Pointers to objects in unordered_maps (C++),
std::unordered_map pointers/reference invalidation和
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/)
尽管希望有人在此再次确认。
最佳答案
根据cppreference:
这意味着指针也不会无效。这是可能的,因为从概念上可以将std::unordered_map
视为std::vector<std::forward_list<std::pair<Key, Value>>>
。而且由于std::forward_list
与其他任何链表一样,是分别分配每个元素的,因此对列表的更改不会影响其元素的内存位置。
关于c++ - unordered_map指向元素值的指针在调整大小后有效吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53149145/