C++ std::throw_with_nested()在内存不足条件调用std::terminate()时
我一直在通过随机生成C++ std::throw_with_nested()在内存不足条件调用std::terminate()时,c++,exception,out-of-memory,nested-exceptions,C++,Exception,Out Of Memory,Nested Exceptions,我一直在通过随机生成malloc()returnnullptr来测试一个类,特别是在内存不足的情况下。它使用嵌套的异常 假设我有以下代码: static std::unordered_map<size_t, size_t> map; try { map.at(0); // Throws std::out_of_range } catch (...) { std::throw_with_nested(std::runtime_error("Input not in ma
malloc()
returnnullptr
来测试一个类,特别是在内存不足的情况下。它使用嵌套的异常
假设我有以下代码:
static std::unordered_map<size_t, size_t> map;
try {
map.at(0); // Throws std::out_of_range
} catch (...) {
std::throw_with_nested(std::runtime_error("Input not in map")); // Out of memory here
}
这是符合标准的预期行为吗?就个人而言,如果无法分配嵌套异常,它感觉应该覆盖旧异常或抛出
std::bad_alloc
。据我所知,std::nested_exception
的构造函数和全局函数std::current_exception()
都是noexcept
,因此,如果其中任何一个发生异常,唯一允许的操作过程是std::terminate
,据我所知,std::nested_exception
的构造函数和全局函数std::current_exception()
都是noexcept
,因此如果其中一个发生异常,根据cppreference.com,唯一允许的操作过程是std::terminate
,std::current_exception()将只返回在调用过程中引起的异常。@josefx您是对的。这样就剩下外部异常的构造函数了。例如,std::runtime\u错误包含std::字符串。如果在抛出过程中抛出,我认为这将被终止。堆栈跟踪指向std::throw_内部,但有_嵌套,因此根据cppreference.com std::current_exception()的说法,std::runtime_错误的构造似乎没有问题(否则它将永远不会调用std::throw_with_嵌套)将只返回调用本身期间引起的异常。@josefx您说得对。这样就剩下外部异常的构造函数了。例如,std::runtime\u错误包含std::字符串。如果在抛出过程中抛出,我认为这将被终止。堆栈跟踪指向std::throw\u内部,但带有嵌套的\u,因此std::runtime\u错误的构造似乎没有问题(否则它将永远不会调用带有嵌套的std::throw\u)
terminate called after throwing an instance of 'std::out_of_range'
what(): _Map_base::at
Program received signal SIGABRT, Aborted.
0x00007ffff6d96418 in __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:54
54 ../sysdeps/unix/sysv/linux/raise.c: No such file or directory.
(gdb) bt
#0 0x00007ffff6d96418 in __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:54
#1 0x00007ffff6d9801a in __GI_abort () at abort.c:89
#2 0x00007ffff76d884d in __gnu_cxx::__verbose_terminate_handler() () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#3 0x00007ffff76d66b6 in ?? () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#4 0x00007ffff76d6701 in std::terminate() () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#5 0x00007ffff76d5472 in __cxa_allocate_exception () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#6 0x0000000000425d4c in std::_Throw_with_nested_impl<std::runtime_error, true>::_S_throw<std::runtime_error>(std::runtime_error&&) (
__t=<unknown type in /path/to/<redacted>, CU 0x2a2a, DIE 0xae780>) at /usr/include/c++/5/bits/nested_exception.h:100
#7 0x000000000041d09f in std::throw_with_nested<std::runtime_error>(std::runtime_error&&) (__t=<unknown type in /path/to/<redacted>, CU 0x2a2a, DIE 0xa3e18>)
at /usr/include/c++/5/bits/nested_exception.h:137