You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++函数返回迭代器异常:迭代器自增后崩溃排查求助

问题描述

我尝试编写一个接收list和索引的函数,返回指向该list指定索引位置的迭代器。

函数代码如下:

template<class T>
typename std::list<T>::iterator begin_it_at_index(list<T> list_to_iterate_on, const int index)
{
  return next(list_to_iterate_on.begin(), index);
}

调用该函数时,虽能获取指定索引的第一个元素,但对迭代器执行++操作后未指向后续元素,反而导致程序崩溃。

调用代码:

#include <iostream>
#include <list>
#include <iterator>

using namespace std;

// 上述函数定义

int main() {
    list<int> temp = {10,20,50,100};
    for (auto it = begin_it_at_index(temp, 1); it != temp.end(); ++it)
    {
        cout << *it << endl;
    }
    return 0;
}

输出结果:

20
74211408
Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)

请问我哪里出错了?


错误分析与修正

核心问题:值传递导致的悬空迭代器

你的函数参数list<T> list_to_iterate_on采用值传递,调用函数时会生成原列表的临时拷贝。函数返回的迭代器指向的是这个临时拷贝的元素,但函数执行完毕后,临时拷贝会被立即销毁,此时返回的迭代器就变成了悬空迭代器——指向已经被释放的内存空间。

第一次能输出20只是巧合(临时对象销毁后内存尚未被其他数据覆盖),但后续对迭代器执行++或解引用操作时,访问的是无效内存,直接触发段错误(SIGSEGV)。

修正方案

将函数参数改为引用传递,让迭代器指向原列表而非临时拷贝:

template<class T>
typename std::list<T>::iterator begin_it_at_index(list<T>& list_to_iterate_on, const int index)
// 参数添加&,改为引用传递
{
  return next(list_to_iterate_on.begin(), index);
}

如果函数不需要修改原列表,建议使用const引用并返回const迭代器,保证代码的const正确性:

template<class T>
typename std::list<T>::const_iterator begin_it_at_index(const list<T>& list_to_iterate_on, const int index)
{
  return next(list_to_iterate_on.cbegin(), index);
}

额外建议

务必检查传入的索引合法性,避免越界访问导致未定义行为:

template<class T>
typename std::list<T>::iterator begin_it_at_index(list<T>& list_to_iterate_on, const int index)
{
    if (index < 0 || static_cast<size_t>(index) >= list_to_iterate_on.size()) {
        throw std::out_of_range("Index exceeds list size");
    }
    return next(list_to_iterate_on.begin(), index);
}

内容的提问来源于stack exchange,提问作者Cs enthusiast

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 05:45:47