下面是发生这个错误的函数:
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 "_";
而引发的。
我是犯了一个基本错误还是真的很奇怪?
最佳答案
terminate called after throwing an instance of 'std::out_of_range'
terminate
被调用通常是由于异常“转义”了析构函数。
what(): vector::_M_range_check: __n (which is 0) >= this->size() (which is 0)
这通常在您对 std::vector
中的元素进行检查访问(想想 .at()
)时抛出。
因此,在 File
析构函数中寻找错误的检查 vector 访问。更好的是,要调试此类问题,请在调试器中运行您的程序,甚至可以在抛出的异常上添加断点(或在 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)
关于c++ - 为什么在这个函数中抛出这个 std::out_of_range ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37647877/