Why is comparing against quot;end()quot; iterator legal?(为什么要与“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()"比较?迭代器合法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么要与“end()"比较?迭代器合法吗?
基础教程推荐
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 这个宏可以转换成函数吗? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
