21

以下是否根据 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?

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

4

2 回答 2

25

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

§23.2.1 [container.requirements.general] p6

begin()返回一个引用容器中第一个元素的迭代器。end()返回一个迭代器,它是容器的结束值。如果容器是空的,那么begin() == end()

表 107§24.2.3 [input.iterators]要求作为 , 的先决条件++itit应该是可取消引用的,这对于过去的迭代器(即,你从 中得到的end())不是这种情况,因此你正在涉足未定义行为的可怕领域。

于 2012-05-29T05:25:22.003 回答
7
std::list<int> myList;
std::list<int> myIter = myList.begin();

迭代器的值与使用myList.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
于 2012-05-29T05:20:29.923 回答