1

Would reference to values in std::map or std::unordered_map be valid/maintained if the map's being inserted new elements or removed from? For example, is the below code safe? Or would there be dangling references from any edge cases or map implementation variations.

std::map<string,SpecialType> myMap({{"Test",{}},{"something",{}},{"Test3",{}}});
auto pointer = &myMap["Test"];
myMap.erase("something");
pointer->DoSomething();
myMap["newItem"] = SpecialType();
pointer->DoSomething();```
Evg
  • 25,259
  • 5
  • 41
  • 83
Xero
  • 23
  • 1
  • 5
  • 1
    As long as you don't erase the item being pointed to you are OK, [reference](https://en.cppreference.com/w/cpp/container#Iterator_invalidation) – john Nov 27 '22 at 14:33
  • 1
    i think the dupe is wrong - there are no iterators in the op's code – Neil Butterworth Nov 27 '22 at 14:39
  • @NeilButterworth though it does talk about iterators the rules for iterators and references are generally the same for most containers – Alan Birtles Nov 27 '22 at 14:58
  • You can change the value of the key-value pair. You cannot change the key of the key-value pair. – Eljay Nov 27 '22 at 15:01
  • @NeilButterworth I still voted to close as duplicate because the answers are covering references and pointers as well. I think the question should just include these in the wording as well. – user17732522 Nov 27 '22 at 18:33

0 Answers0