您似乎认为“无效”迭代器只有在使用时会引发崩溃,但标准的定义更广泛。它包括迭代器仍然可以安全地被取消引用,但不再指向它预期指向的元素的可能性。 (这是观察到“未定义行为”并不意味着“您的程序将立即崩溃”的一个特例;它也可能意味着“您的程序将默默地计算错误的结果”甚至“什么都没有” 这个实现会出现明显错误。")
使用erase 更容易说明为什么这是一个问题:
#include <vector>
#include <iostream>
int main(void)
{
std::vector<int> a { 0, 1, 2, 3, 4, 4, 6 };
for (auto p = a.begin(); p != a.end(); p++) // THIS IS WRONG
if (*p == 4)
a.erase(p);
for (auto p = a.begin(); p != a.end(); p++)
std::cout << ' ' << *p;
std::cout << '\n';
}
在 C++ 的典型实现中,该程序不会崩溃,但它会打印 0 1 2 3 4 6,而不是像预期的那样打印 0 1 2 3 6,因为擦除第一个 4 无效 p - - 通过将其推进到第二个4。
您的 C++ 实现可能有一个特殊的“调试”模式,在该模式下,该程序在运行时确实崩溃。例如,使用 GCC 4.8:
$ g++ -std=c++11 -W -Wall test.cc && ./a.out
0 1 2 3 4 6
但是
$ g++ -std=c++11 -W -Wall -D_GLIBCXX_DEBUG test.cc && ./a.out
/usr/include/c++/4.8/debug/safe_iterator.h:307:error: attempt to increment
a singular iterator.
Objects involved in the operation:
iterator "this" @ 0x0x7fff5d659470 {
type = N11__gnu_debug14_Safe_iteratorIN9__gnu_cxx17__normal_iteratorIPiNSt9__cxx19986vectorIiSaIiEEEEENSt7__debug6vectorIiS6_EEEE (mutable iterator);
state = singular;
references sequence with type `NSt7__debug6vectorIiSaIiEEE' @ 0x0x7fff5d659470
}
Aborted
请理解该程序会引发未定义的行为无论哪种方式。只是未定义行为的后果在调试模式下更加戏剧化。