C 11 forward_list迭代器仍指向删除值

C++11 forward_list iterator remains pointing to removed value

本文关键字:删除 迭代器 forward list      更新时间:2023-10-16

迭代器仍指向先前所做的元素,并且指向其指向的值不会从内存中删除。我想知道如何解释?谢谢。

forward_list<int> Fwdl {46, 21, 88, 901, 404};
auto it = Fwdl.begin();
Fwdl.remove(46);
cout << "List : "; for(int& elem : Fwdl) cout << " " << elem; cout << endl;
//This prints "List : 21 88 901 404" as expected, but:
cout << "Iterator is alive! " << *it << endl;
//This still prints "Iterator is alive! 46"

N4431-23.3.5.5/15列表操作[list.ops] (强调我的)

void remove(const T& value);
template <class Predicate> void remove_if(Predicate pred);

效果:删除列表迭代器i所述的所有列表中的所有元素,其中以下条件保持:*i == value, pred(*i) != false仅无效迭代器和对擦除元素的引用

您拥有的是不确定行为的典型表现,您不应依靠此类代码。

可能发生的事情与此类似:

int* p = new int(42);
int* iterator = p;
delete p;
// may still display 42, since the memory may have not yet been reclaimed by the OS, 
// but it is Undefined Behaviour
std::cout << *iterator; 

正如其中一条评论中所述,解除无效的迭代器是不确定的行为。在您的情况下,它可能仍指向元素过去所在的堆的空间,并且还没有被其他事物覆盖。在不同的编译器或程序的其他运行中,它本来可以是Jibbersish或完全崩溃了程序。