为什么要与“end()"比较?迭代器合法吗?

Why is comparing against quot;end()quot; iterator legal?(为什么要与“end()比较?迭代器合法吗?)
本文介绍了为什么要与“end()"比较?迭代器合法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 C++ 标准 (3.7.3.2/4) 使用(不仅是取消引用,还包括复制、强制转换等)无效指针是未定义的行为(如有疑问,请参阅 这个问题).现在遍历 STL 容器的典型代码如下所示:

According to C++ standard (3.7.3.2/4) using (not only dereferencing, but also copying, casting, whatever else) an invalid pointer is undefined behavior (in case of doubt also see this question). Now the typical code to traverse an STL containter looks like this:

std::vector<int> toTraverse;
//populate the vector
for( std::vector<int>::iterator it = toTraverse.begin(); it != toTraverse.end(); ++it ) {
    //process( *it );
}

std::vector::end() 是假设元素的迭代器超出容器的最后一个元素.那里没有元素,因此通过该迭代器使用指针是未定义的行为.

std::vector::end() is an iterator onto the hypothetic element beyond the last element of the containter. There's no element there, therefore using a pointer through that iterator is undefined behavior.

现在 != end() 是如何工作的呢?我的意思是为了进行比较,需要构造一个迭代器来包装一个无效地址,然后必须在比较中使用该无效地址,这又是未定义的行为.这种比较合法吗?为什么?

Now how does the != end() work then? I mean in order to do the comparison an iterator needs to be constructed wrapping an invalid address and then that invalid address will have to be used in a comparison which again is undefined behavior. Is such comparison legal and why?

推荐答案

你是对的,一个无效的指针不能被使用,但是你错了,一个指向一个元素的指针在数组中的最后一个元素之后是一个无效的指针 - 它是有效的.

You're right that an invalid pointer can't be used, but you're wrong that a pointer to an element one past the last element in an array is an invalid pointer - it's valid.

C 标准第 6.5.6.8 节说它定义明确且有效:

The C standard, section 6.5.6.8 says that it's well defined and valid:

...如果表达式 P 指向数组对象的最后一个元素,表达式 (P)+1 点过去数组对象的最后一个元素...

...if the expression P points to the last element of an array object, the expression (P)+1 points one past the last element of the array object...

但不能取消引用:

...如果结果指向超过数组对象的最后一个元素,它不得用作 a 的操作数被评估的一元 * 运算符...

...if the result points one past the last element of the array object, it shall not be used as the operand of a unary * operator that is evaluated...

这篇关于为什么要与“end()"比较?迭代器合法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)