Lifetime of references in STD collections

旧城冷巷雨未停 提交于 2019-12-08 18:16:34

问题


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]


回答1:


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



来源:https://stackoverflow.com/questions/23600400/lifetime-of-references-in-std-collections

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!