#include<list>
#include<iostream>

using namespace std;

list<int> DL,TRS;
list<int>::iterator gitr;

void exchange();

int main() {
  DL.push_back(10);
  gitr=DL.begin();
  TRS.push_back(11);
  TRS.push_back(12);
  exchange();
  cout<<(*gitr)<<endl;
}

void exchange() {
  list<int> tdl;
  tdl=DL;
  DL.clear();
  DL=TRS;
  list<int>::iterator tmpitr=DL.begin();
  for(;tmpitr!=DL.end();++tmpitr)
     cout<<(*tmpitr)<<endl;
  DL.clear();
  DL=tdl;
}

这将输出11而不是10。为什么?

最佳答案

该程序会调用未定义的行为,因此可以执行所需的任何操作,甚至可以打印11而不是10。

为什么是UB?因为gitr被分配了DL.begin(),然后(在exchange函数内部)被清除了DL,所以gitr成为无效的迭代器。取消引用迭代器为UB。

10-08 07:02
查看更多