STD系列中的参考文献的生命周期

编程入门 行业动态 更新时间:2024-10-28 04:23:33
本文介绍了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?

}

换句话说,我从地图获取值引用。但是,然后我做了各种其他插入,删除等等的底层地图。原值参考还好吗?对于其他收藏品呢?

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等地方有很好的记录。

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.

概括地说, 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系列中的参考文献的生命周期

本文发布于:2023-10-09 10:41:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1475519.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:参考文献   生命周期   系列   STD

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!