简体   繁体   English

向量中的无效迭代器

[英]Invalidated iterator in a vector

I'm aware erasing will invalidate iterators at and after the point of the erase. 我知道擦除会在擦除点之后和之后使迭代器无效。 Consider: 考虑:

std::vector<int> vec = {1, 2, 3, 4, 5};
std::vector<int>::iterator it = vec.end() - 1; //last element
vec.erase(vec.begin()); //shift everything one to the left, 'it' should be the new 'end()' ?
std::cout << (it == vec.end()); //not dereferencing 'it', just comparing, UB ?

Is it undefined behavior to compare (not dereference) an invalidated iterator ( it in this case)? 它是不确定的行为进行比较(不提领)被无效的迭代器( it在这种情况下)? If not, is it == vec.end() guaranteed to hold true? 如果没有,是否保证it == vec.end()保持为真?

Edit : from the top answer it looks like this is UB if only it is a singular value . 编辑 :从顶部答案看,如果it只是一个奇异值,它就像是UB。 But from What is singular and non-singular values in the context of STL iterators? 但是在STL迭代器的上下文中什么是单数和非奇异值? it seems like it is (or was ) associated with the container hence making it non-singular . 似乎it (或曾经 )与容器相关联,因此使其it 非单数形式

I'd appreciate further analysis on this, thank you. 我很感激对此进行进一步的分析,谢谢。

Once your iterator has been invalidated, it may be UB to even compare it to something else: 一旦你的迭代器失效,甚至可以将UB与其他东西进行比较:

[C++14: 24.2.1/10]: An invalid iterator is an iterator that may be singular. [C++14: 24.2.1/10]: 无效的迭代器是一个可能是单数的迭代器。

[C++14: 24.2.1/5]: [..] Results of most expressions are undefined for singular values; [C++14: 24.2.1/5]: [..]大多数表达式的结果未定义为奇异值; the only exceptions are destroying an iterator that holds a singular value, the assignment of a non-singular value to an iterator that holds a singular value, and, for iterators that satisfy the DefaultConstructible requirements, using a value-initialized iterator as the source of a copy or move operation. 唯一的例外是破坏一个包含奇异值的迭代器,一个非奇异值赋值给一个包含奇异值的迭代器,对于满足DefaultConstructible要求的迭代器,使用一个值初始化的迭代器作为源复制或移动操作。 [..] [..]

Note that this means you also can't compare a default-constructed iterator to any .end() . 请注意,这意味着您也无法将默认构造的迭代器与任何.end()

Contrary to popular belief that "pointers are just memory addresses", these rules are also largely true for pointers. 与普遍认为“指针只是内存地址”相反,这些规则对于指针来说也是如此。 Indeed, the rules for iterators are a generalisation of the rules for pointers. 实际上,迭代器的规则是指针规则的概括。

Formally any iterator pointing to an element on or after the erased element is invalidated. 正式地,指向擦除元素上或之后的元素的任何迭代器都将失效。 So 所以

  1. Yes this is UB (despite it being a pointer under the hood.) 是的,这是UB(尽管它是引擎盖下的指针。)

  2. UB again, despite the obvious plausibility. UB再次,尽管有明显的合理性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM