Std::throw_with_nested()在内存不足的情况下调用Std::terminate()

std::throw_with_nested() on out of memory condition calls std::terminate()

本文关键字:Std 情况下 调用 terminate nested throw with 内存不足      更新时间:2023-10-16

我一直在测试一个类的异常保证,特别是在内存不足的情况下,通过随机使malloc()返回nullptr。它使用嵌套异常。

假设我有以下代码:

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::throw_with_nested()最终调用std::terminate():

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

这是按照标准预期的行为吗?个人认为,如果分配嵌套异常失败,它应该覆盖旧的异常或抛出std::bad_alloc

据我所知,std::nested_exception的构造函数和全局函数std::current_exception()都是noexcept,所以如果其中任何一个发生异常,唯一允许的操作过程是std::terminate

相关文章: