当list为空时,std :: list:begin()的行为

时间:2012-05-29 05:16:00

标签: c++ std

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

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?

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

2 个答案:

答案 0 :(得分:18)

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

§23.2.1 [container.requirements.general] p6

  

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

§24.2.3 [input.iterators]中的表107要求作为++it的前提条件,it应该是可解除引用的,而对于过去的结束迭代器则不是这样(即,你是什么从end()获取,因此你正在进入未定义行为的可怕领域。

答案 1 :(得分:4)

std::list<int> myList;
std::list<int> myIter = myList.begin();

迭代器具有与使用myList.end()初始化迭代器时相同的值。迭代器初始化为on-last-the-end位置。即使将元素推入列表后,迭代器仍然指向一个接一个的结尾。如果递增它,则调用未定义的行为。

更新:

例如,如果使用-D_GLIBCXX_DEBUG使用GCC编译代码段,则生成的可执行文件将中止:

/usr/include/c++/4.6/debug/safe_iterator.h:236:error: attempt to increment 
    a past-the-end iterator.

Objects involved in the operation:
iterator "this" @ 0x0x7fffc9548fb0 {
type = N11__gnu_debug14_Safe_iteratorINSt9__cxx199814_List_iteratorIiEENSt7__debug4listIiSaIiEEEEE (mutable iterator);
  state = past-the-end;
  references sequence with type `NSt7__debug4listIiSaIiEEE' @ 0x0x7fffc9548fb0
}
zsh: abort (core dumped)  ./listiter