为什么要与“end()"比较?迭代器合法吗? [英] Why is comparing against "end()" iterator legal?

查看:17
本文介绍了为什么要与“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()"比较?迭代器合法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆