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

查看:225
本文介绍了为什么要与“end()”进行比较,迭代器合法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据C ++标准(3.7.3.2/4)使用(不仅取消引用,而且复制,转换,无论什么)一个无效的指针是未定义的行为(如果疑惑, a href =http://stackoverflow.com/questions/1866461/why-should-i-not-try-to-use-this-value-after-delete-this>此问题)。现在,遍历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 / code>是超过超过包含器的最后一个元素的假设元素的迭代器。没有元素,因此使用通过迭代器的指针是未定义的行为。

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指向数组对象的
last元素,
expression(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...

取消引用:


...如果结果指向数组对象的
last元素,则
不能用作被计算的
一元运算符的操作数...

...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天全站免登陆