C 11 forward_list迭代器仍指向删除值
C++11 forward_list iterator remains pointing to removed value
迭代器仍指向先前所做的元素,并且指向其指向的值不会从内存中删除。我想知道如何解释?谢谢。
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或完全崩溃了程序。
相关文章:
- 使用迭代器 C++ 删除矢量中的重叠字符串
- C++:在进行切片时对迭代器的约定,特别是对于访问最后一个元素并最终将其删除
- 如何使用擦除和迭代器来删除二维向量中的项目
- 如果我有一个指向矢量元素的指针,而不是迭代器,如何删除它?
- c++ 在循环中删除迭代器(映射的映射)
- 从矢量C++中删除时,矢量迭代器不可取消引用
- 为什么擦除-删除成语不适用于反向迭代器
- 通过反向迭代器从矢量快速删除
- debug断言矢量迭代器不可用find_if删除
- 如何在不使用循环或迭代器的情况下检查所有列表元素并在满足条件时删除一个
- 如何在给定迭代器列表的情况下从向量中删除元素
- 射击时从列表中删除外星人 - 找出循环;"表达式:无法递增结束列表迭代器"
- 使用迭代器指针 (C++) 从对象指针列表中删除元素
- 为什么删除字符串迭代器会产生const char参考
- 迭代器:如果 '*' 返回元素的引用,为什么删除 *(myList.end()) 会给出 SegFault
- 在迭代器时从 std::list 中删除条目
- 如何使用反向迭代器从“std::set”中删除元素
- C++:从映射中删除迭代器,然后递增到下一个迭代器
- erase删除迭代器所指向的元素失败时的处理方法
- c++不需要删除迭代器