以下是否给出了根据 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?
我可以在我正在使用的编译器上测试这一点......但我想要一个更明确的答案。
这是一个与关于空向量的问题不同的问题,因为它涉及询问容器不再为空()之后迭代器的状态。
所有标准迭代器和容器类型在这方面的行为都是相同的:
§23.2.1 [container.requirements.general] p6
返回一个引用容器中第一个元素的迭代器。begin()
返回一个迭代器,它是容器的最后值。 如果容器是空的,则end()
;begin() == end()
§24.2.3 [input.iterators]
中的表107要求作为++it
的先决条件,it
应该是可解引用的,而尾后迭代器则不是这种情况(即,从end()
得到的),如下这样你就进入了未定义行为的可怕领域。
std::list<int> myList;
std::list<int> myIter = myList.begin();
迭代器具有与使用
myList.end()
初始化它相同的值。迭代器被初始化到结束位置。即使将一个元素推入列表后,迭代器仍然指向末尾一位。如果您增加它,您将调用未定义的行为。
更新:
例如,如果您使用 GCC 和 -D_GLIBCXX_DEBUG 编译代码片段,生成的可执行文件将中止:
/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