为什么在这个函数中抛出这个std :: out_of_range?

时间:2016-06-05 23:45:55

标签: c++

以下是发生此错误的函数:

std::string DataTranslation::getMeshName(std::string meshLink)
{
    File input(this->datafilename);
    std::cout << "the line count of " << this->datafilename << " = " << input.lineCount() << ".\n";
    std::cout << "code above is working properly if this prints.\n";
    return "_";
}

运行时:

the line count of ./res/data/resourcelist.data = 6.
code above is working properly if this prints.
terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check: __n (which is 0) >= this->size() (which is 0)

这就是字面意思。以前,这个功能要复杂得多,而且在调试过程中,我对它进行了全面的评论,让我了解上面所写的内容。由于return "_";,似乎引发了异常。

我是犯了一个基本错误还是确实这么奇怪?

1 个答案:

答案 0 :(得分:1)

terminate called after throwing an instance of 'std::out_of_range'
被调用的{p> terminate通常是由于异常&#34;逃避&#34;析构函数。

what(): vector::_M_range_check: __n (which is 0) >= this->size() (which is 0)

当您对.at()中的元素进行检查访问(请std::vector)时,通常会抛出此内容。

因此,在File析构函数中查找错误的已检查向量访问。更好的是,调试此类问题在调试器中运行程序,甚至可能在抛出的异常(或std::terminate之上)添加断点;请注意,gdb这不应该是必要的 - std::terminate会产生SIGABRT,这会自动进入调试器。

(gdb) r
Starting program: /home/matteo/scratch/a.out 
terminate called after throwing an instance of 'int'

Program received signal SIGABRT, Aborted.
0x00007ffff76c1418 in __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:54
54      ../sysdeps/unix/sysv/linux/raise.c: File o directory non esistente.
(gdb) bt
#0  0x00007ffff76c1418 in __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:54
#1  0x00007ffff76c301a in __GI_abort () at abort.c:89
#2  0x00007ffff7ae484d in __gnu_cxx::__verbose_terminate_handler() ()
   from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#3  0x00007ffff7ae26b6 in ?? () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#4  0x00007ffff7ae2701 in std::terminate() () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#5  0x00007ffff7ae2919 in __cxa_throw () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#6  0x000000000040077e in A::~A() ()
#7  0x0000000000400729 in foo() ()
#8  0x0000000000400749 in main ()
(gdb)