C++ Storing references to values in std::map
c++, reference, stdmap
Solution
The Standard is clear on this in `23.1.2/8` about associative containers
The insert members shall not affect the validity of iterators and references to the container, and the erase members shall invalidate only iterators and references to the erased elements.
Problem
Am I right in assuming that adding/removing elements to an std::map does not effect the other elements (ie cause them to be relocated in memory) and so that the following is safe: I looked at various sites with info on the container but only found out about the cases where iterators are invalidated, which I already know... ``` std::map<std::string,std::string> map; PopulateMap(map); std::string &a= map["x"]; AddMoreData(map); RemoveRandomKeysExceptX(map); map["x"] = "foo"; std::cout << a << " " << map["x"] << std::endl;//prints "foo foo" a = "bar"; std::cout << a << " " << map["x"] << std::endl;//prints "bar bar" ``` I tested some similar code on VC9, which seems to work however that doesn't mean I didn't just get lucky or that it doesn't vary across compilers.