gpt4 book ai didi

c++ - 将全局迭代器重置为列表

转载 作者:行者123 更新时间:2023-11-30 04:33:38 24 4
gpt4 key购买 nike

#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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com