Which operations are defined for invalid iterators?

◇◆丶佛笑我妖孽 提交于 2019-12-20 02:14:03

问题


As a follow-up on a question concerning comparing invalid iterators, I tried to find a definition of the allowed expressions for invalid iterators in the C++ standard. Searching for "invalid iterator" finds only a single reference in §24.2.1.11. It says that invalid iterators may be "singular", but only states that dereferencing them may be undefined behavior. No further semantics is given.

One of the original answers suggests that it is implementation-defined behavior, but I think that this cannot be assumed in general because the above mentioned paragraph explicitly refers to UB.

This answer shows that "Any other use of an invalid pointer value has implementation-defined behavior". Since iterators for vectors are often implemented as pointers, I would argue that comparing two invalid iterators is at least implementation-defined behavior.

Could anybody point me to the relevant sections in the standard where the semantics for invalid iterators are defined?


回答1:


Maybe [iterator.requirements.general, 24.2.1]/6 contains what you're after?

Results of most expressions are undefined for singular values; 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. [Note: This guarantee is not offered for default initialization, although the distinction only matters for types with trivial default constructors such as pointers or aggregates holding pointers. — end note] In these cases the singular value is overwritten the same way as any other value. Dereferenceable values are always non-singular.

Moreover, invalid iterators are defined by paragraph 11:

An invalid iterator is an iterator that may be singular.

Thus, invalid iterators are at least as constrained as singular iterators; specifically, the only permitted operations are destruction and assignment.



来源:https://stackoverflow.com/questions/33076032/which-operations-are-defined-for-invalid-iterators

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