unordered_map pointer to element's value valid after resize?

  • A+

If I have an unordered_map<key, someNiceObject>

(note someNiceObject is not a pointer)

I have an API which inserts a new element, then returns a pointer to someNiceObject now in the map.

If I perform further insertions into the map, there could be a capacity change. If that happens is the pointer still valid or not?

I tried reading Basic questions: Pointers to objects in unordered_maps (C++), std::unordered_map pointers/reference invalidation and

and couldn't locate the necessary information

Thanks all

edit: it seems that the pointer would be valid (

though would appreciate a second confirmation from someone here on SO.


std::unordered map is unusual in that the iterator invalidation rules do NOT apply to references to elements (excluding removal but what can you do when the item is gone?). A capacity change is not important. The problem is when the unordered map rehashes. Rehashing will invalidate all iterators, but will not invalidate references.

From point 9 of [unord.req] in the C++ Standard (citing n4618 because that's what I have on hand at the moment),

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.

emphasis mine


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: