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

时间:2016-09-14 17:30:09

标签: c++ exception out-of-memory nested-exceptions

我一直是强大的异常保证,通过随机调用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

1 个答案:

答案 0 :(得分:0)

据我了解,std::nested_exception的构造函数和全局函数std::current_exception()都是noexcept,所以如果任何一个都发生异常,那么唯一允许的行动方案是std::terminate