8

How long is a reference to an element returned by an STD collection, such as a map, valid?

For example, in this code:

struct Employee{
   int salary;
   string name; // the key
     };

map<string,Employee> allemployees;
...
Employee & Joe = allemployees["Joe Smith"];
Joe.salary=150; // change "Joe Smith"'s salary
assert(allemployees["Joe Smith"].salary==150); //always true
 ....
allemployees["Mark Jones"]= Employee();
... // No "Joe Smith" operations in the dots
 Joe.salary=200;
 assert (allemployees["Joe Smith"].salary==200); //true or not?

}

In other words, I get a value reference back from a map. But then I do various other insertions, deletions and so on the underlying map. Is the original value reference still good? What about for other collections?

And also, how do I know that? I looked in Stroustrup but did not see anything.

Coming from a C background I am confused by references and collections and their interaction. Should I ever consider maps whose values are references themselves? What would that even mean?

So a more general question: where do I find normative answers to this question and similar kinds of questions?

[This is the revised version of a deleted question]

kdog
  • 1,583
  • 16
  • 28

1 Answers1

11

std::map references are invalidated by the same actions that would invalidate an iterator - that's well documented in the Standard and places like cppreference.com.

Summarily for std::map, the references are valid as long as you don't clear the map, or erase the specific referenced element; inserting or erasing other elements is fine. For example, cpprefererence map::insert documentation says "No iterators or references are invalidated.".

You'll find there are statements about other containers and their operations.... (jrok pointed out in comments that push to deque is an example of an operation where references remain valid but iterators are invalidated).

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252
  • OK thanks. What about the semantics of using a map whose value type is a reference, e.g. map . Am I guaranteed that, for instance, nothing the map does will affect the underlying Employee it points to? – kdog May 12 '14 at 03:15
  • 1
    @kdog: you can't have "a map whose value type is a reference"... not allowed. See e.g. [here](http://stackoverflow.com/questions/2934021/stl-map-containing-references-does-not-compile) – Tony Delroy May 12 '14 at 03:22
  • @TonyD I'm curious, where in the standard does it say this? – Brian Bi May 12 '14 at 03:30
  • 1
    The C++11 specification clearly states (§23.2.1[container.requirements.general]/1):Containers are objects that store other objects. – user2672165 May 12 '14 at 05:07
  • 1
    There are cases where iterators are invalidated but references are not, such as pushing to `deque`. – jrok May 12 '14 at 05:52
  • 1
    Thanks, I appreciate the great answer and the pointer (or reference) to other sources of information as well. – kdog May 12 '14 at 06:08