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"
如评论之一所述,取消引用无效的迭代器是未定义的行为。在您的情况下,它可能仍然指向元素曾经所在的堆上的 space ,并且尚未被其他内容覆盖。在不同的编译器或程序的不同 运行 上,它可能是乱码或使程序完全崩溃。
N4431 - 23.3.5.5/15 列表操作 [list.ops](强调我的)
void remove(const T& value);
template <class Predicate> void remove_if(Predicate pred);
Effects: Erases all the elements in the list referred by a list iterator i
for which the following conditions hold: *i == value, pred(*i) != false
. Invalidates only the iterators and references to the erased elements.
你所拥有的是未定义行为的典型表现,你不应该依赖这样的代码。
可能发生的事情与此类似:
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;
迭代器仍然指向它之前指向的元素,并且它指向的值不会从内存中删除。我想知道这怎么解释?谢谢。
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"
如评论之一所述,取消引用无效的迭代器是未定义的行为。在您的情况下,它可能仍然指向元素曾经所在的堆上的 space ,并且尚未被其他内容覆盖。在不同的编译器或程序的不同 运行 上,它可能是乱码或使程序完全崩溃。
N4431 - 23.3.5.5/15 列表操作 [list.ops](强调我的)
void remove(const T& value);
template <class Predicate> void remove_if(Predicate pred);
Effects: Erases all the elements in the list referred by a list iterator
i
for which the following conditions hold:*i == value, pred(*i) != false
. Invalidates only the iterators and references to the erased elements.
你所拥有的是未定义行为的典型表现,你不应该依赖这样的代码。
可能发生的事情与此类似:
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;