从列表中删除后,为什么迭代器指向的数据会保留

Chr*_*ris 0 c++ iterator list

在此示例程序中,为什么即使在列表为空之后,迭代器指向的数据的值也会保留?
由于在C++中实现迭代器(即对象的值保存在迭代器中),是否会发生某种情况,或者是因为内存段被声明为免费使用,但尚未更改?

#include <iostream>
#include <list>
using namespace std;
int main ()
{
    list<int> mylist;
    list<int>::iterator it = mylist.begin();
    cout << "printing: " << *it << endl;

    mylist.push_back(77);
    mylist.push_back(22);

    // now front equals 77, and back 22

    mylist.front() -= mylist.back();
    it = mylist.begin();
    cout << "printing: " << *it << endl;
    cout << "mylist.front() is now " << mylist.front() << '\n';
    // trying to delete all elements and then see how the iterators are handling it
    it = mylist.begin();
    cout << "printing: " << *it << endl;
    mylist.remove(55);
    cout << "printing: " << *it << endl;
    mylist.remove(22);
    cout << "printing: " << *it << endl;
    cout << "mylist size: " << mylist.size() << endl;
    cout << "mylist.front() is now " << mylist.front() << '\n';
    cout << "printing: " << *it << endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是输出:

printing: 495034304
printing: 55
mylist.front() is now 55
printing: 55
printing: 55
printing: 55
mylist size: 0
mylist.front() is now 38375440
printing: 55
Run Code Online (Sandbox Code Playgroud)

Mik*_*our 6

由于在C++中实现了迭代器,它是否会发生一些事情

不,这是未定义的行为.迭代器已变为无效,无法使用.

是因为内存段被宣布为免费使用,但尚未更改?

是的,这就是你观察你所观察到的东西的原因.但是内存可以被重用于其他东西,或者无法访问 - 你不能依赖任何未定义行为的观察.