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

oma*_*tai 15 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?
Run Code Online (Sandbox Code Playgroud)

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

Xeo*_*Xeo 19

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

§23.2.1 [container.requirements.general] p6

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

并且表107 §24.2.3 [input.iterators]要求作为前提条件++it,it应该是可解除引用的,而不是过去的结束迭代器(即,你得到的东西end())的情况,因此你正在进入未定义行为的可怕领域.


wil*_*ilx 7

std::list<int> myList;
std::list<int> myIter = myList.begin();
Run Code Online (Sandbox Code Playgroud)

迭代器的值与您使用myList.end(). 迭代器被初始化为 on-past-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
Run Code Online (Sandbox Code Playgroud)

  • @omatai:`std::list&lt;&gt;` 不是循环的。 (6认同)