2016-09-14 81 views
1

我一直强烈的例外保证测试一个类,特别是在内存不足的情况下发生了什么,通过随机发出malloc()返回nullptr。它使用嵌套异常。std :: throw_with_nested()在内存不足条件调用std :: terminate()

比方说,我有以下代码:

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 ([email protected]=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 ([email protected]=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

回答

0

据我了解,中std::nested_exception两个构造函数和全局函数std::current_exception()noexcept,所以如果有异常的任何一个发生时,动作的唯一允许当然是std::terminate

+0

根据cppreference.com std :: current_exception()将只返回在调用本身引起的异常。 – josefx

+0

@josefx你是对的。这样就留下了外部异常的构造函数。例如,std :: runtime_error包含一个std :: string。如果抛出期间抛出,我认为这将终止。 –

+0

虽然堆栈跟踪指向内部的std :: throw_with_nested,所以std :: runtime_error似乎构造没有问题(否则它永远不会有调用std :: throw_with_nested) –

相关问题