在这个示例程序中,为什么在列表为空之后,迭代器指向的数据的值仍然保留?
是由于 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;
}
这是输出:
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
最佳答案
Is it something bound to happen due to the implementation of iterators in C++
不,这是未定义的行为。迭代器已失效,无法使用。
is it because the segment of the memory was declared as free for used, but hasn't been changed yet?
是的,这就是为什么你观察到你所观察到的。但是内存可以重新用于其他用途,或者无法访问 - 您不能依赖对未定义行为的任何观察。
关于c++ - 为什么迭代器指向的数据在从列表中删除后仍保留,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21118372/