References Live Iterators Die

The C++ standard says of unordered containers that rehashing invalidates iterators and changes which buckets elements appear in, but does not invalidate pointers or references to elements, and that insert shall not affect the validity of references while it may invalidate all iterators.

std::unordered_map<int, int> counts;
for (int i = 0; i < 4; i++) counts[i] = 0;
counts.reserve(4);

int &zero = counts[0];
auto it = counts.find(1);

for (int i = 4; i < 1000; i++) counts[i] = i;   // forces several rehashes

zero += 1;             // line A
int v = it->second;    // line B

Which line has undefined behavior?

A

Neither, because reserve fixes the bucket count and prevents any rehash

B

Line B only

C

Line A only

D

Both A and B, since a rehash rebuilds the bucket array and moves every element