作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
#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。
关于c++ - 将全局迭代器重置为列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6666516/
我是一名优秀的程序员,十分优秀!