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]
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With