您似乎认为“无效”迭代器只是使用时会引发崩溃的迭代器,但标准的定义更广泛。它包括迭代器仍然可以安全地取消引用的可能性,但不再指向它期望指向的元素。 (这是“未定义行为”观察的一个特例does not意思是“你的程序将立即崩溃”;它也可能意味着“你的程序将默默地计算出错误的结果”,甚至“不会发生任何明显的错误”this执行。”)
更容易证明为什么这是一个问题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++ 实现可能有一个特殊的“调试”模式,在该模式下该程序does运行时崩溃。例如,对于 GCC 4.8:
$ g++ -std=c++11 -W -Wall test.cc && ./a.out
0 1 2 3 4 6
but
$ 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
请务必了解该程序会引发未定义的行为无论哪种方式。只是在调试模式下未定义行为的后果更为严重。