Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lifetime of references in STD collections

Tags:

c++

std

c++11

map

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]

like image 317
kdog Avatar asked May 12 '14 02:05

kdog


1 Answers

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).

like image 60
Tony Delroy Avatar answered Sep 18 '22 17:09

Tony Delroy