STD集合中引用的生命周期 [英] Lifetime of references in STD collections

查看:194
本文介绍了STD集合中引用的生命周期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对STD集合返回的元素(例如地图)的引用有效期为多长时间?

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

例如,在此代码中:

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?

}

换句话说,I从映射获取值引用。但后来我做了各种其他插入,删除等底层地图。是原值参考还好吗?对于其他集合呢?

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?

还有,我怎么知道呢?我在Stroustrup看过,但没有看到任何东西。

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

来自C背景我被引用和集合及其交互混淆。我应该考虑其值是引用本身的地图吗?

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 引用被无效的迭代器的相同操作无效 - 这在标准和cppreference.com的地方。

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.

简单地为 std :: map ,引用是有效的,只要你不清除 映射擦除插入或删除其他元素是很好的。例如, cpprefererence map :: insert documentation 说没有迭代器或引用无效。

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

你会发现有关于其他容器及其操作的语句....
(jrok在注释中指出, deque 是一个操作的示例,其中引用仍然有效,但迭代器无效)。

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

这篇关于STD集合中引用的生命周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆