列表为空时std :: list:begin()的行为 [英] Behaviour of std::list:begin() when list is empty

查看:568
本文介绍了列表为空时std :: list:begin()的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下内容是否根据C ++标准给出了定义的结果?

Does the following give defined results in terms of the C++ standard?

std::list<int> myList;
std::list<int>::iterator myIter = myList.begin();    // any issues?
myList.push_back( 123 );
myIter++;                                  // will myIter point to the 123 I pushed?

我可以在正在使用的编译器上对此进行测试...但是我想要一个更明确的答案。

I can test this out on the compiler I'm using... but I'd like a more definitive answer.

推荐答案

在这方面,所有标准迭代器和容器类型的行为均相同:

All standard iterator and container types behave the same in this regard:

§23.2.1[container.requirements.general] p6


begin()返回一个迭代器,该迭代器引用容器中的第一个元素。 end()返回一个迭代器,该迭代器是容器的过去值。 如果容器为空,则 begin()== end();

begin() returns an iterator referring to the first element in the container. end() returns an iterator which is the past-the-end value for the container. If the container is empty, then begin() == end();

§24.2.3[input.iterators] 中的表107要求将其作为 ++ it的前提 it 应该是可取消引用的,对于过去的迭代器而言,情况并非如此(即,您从 end()),这样您就可以进入未定义行为的可怕领域。

And table 107 in §24.2.3 [input.iterators] demands that as a precondition for ++it, it shall be dereferenceable, which is not the case for past-the-end iterators (i.e., what you get from end()), as such you're treading into the dreaded domain of undefined behaviour.

这篇关于列表为空时std :: list:begin()的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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