减少begin()迭代器,然后再次增加它 [英] Decreasing begin() iterator and then increasing it again

查看:141
本文介绍了减少begin()迭代器,然后再次增加它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这些语句是否通过标准有效?

Are such statements valid by the standard?

std::string str{"123"};
auto it = str.begin();
--it;
++it; // Does *it point to character '1' now?



我在g ++ 4.7.2和clang ++ 3.5 - it 返回'1'
这是c ++ 11中的标准行为吗?

I've tried this on g++ 4.7.2 and clang++ 3.5 - *it returns '1'. Is this the standard behavior in c++11?

推荐答案

不,它无效。

行为,因为24.2.6 [bidirectional.iterators]声明 - it 的后置条件是结果必须是可解引用的。因为它在 begin()之前,这个条件不满足,因此代码是非法的。

It is undefined behaviour, as 24.2.6 [bidirectional.iterators] states that a postcondition of --it is that the result must be dereferenceable. As it points before begin() in your example, this condition is not met and hence the code is illegal.

因为没有诊断需要,它可能似乎工作,但你不能(也不应该)依靠它。

As there is no diagnostic required it might seem to work, but you can not (and should not) rely on it.

这篇关于减少begin()迭代器,然后再次增加它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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