Std::throw_with_nested()在内存不足的情况下调用Std::terminate()
std::throw_with_nested() on out of memory condition calls std::terminate()
我一直在测试一个类的异常保证,特别是在内存不足的情况下,通过随机使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
。
相关文章:
- 如果 std::vector::clear() 不是静态的,如何在没有实例的情况下调用它?
- 在没有未定义行为的情况下实现类似std::vector的容器
- 如何在没有死锁和/或争用的情况下正确使用 std::mutex C++?
- C++标准是否允许<double>在没有开销的情况下实现 std::可选
- 在这种情况下显式调用时,std::cout 如何更改析构函数的行为?
- 为什么在以下情况下我需要使用 std::d ecay?
- 如何在没有 std::move 的情况下移动临时对象
- 在不使用模板的情况下获取 std::array 引用
- 如何在不使用 std::tm 和 mktime() 的情况下为给定日历日期创建 chrono::time_point 对
- 如何在给定 std::variant 的情况下检索模板参数包?
- 有没有办法在不使用命名空间 std 或前缀 std:: 的情况下引用 cout?
- 在不使用vector.end()的情况下迭代std::vector
- 为什么std::atomic中的所有成员函数都同时出现在有volatile和没有volatile的情况下
- 如何从 std::optional 中获取 QByteArray<QByteArray>,并在没有其他 malloc 的情况下保留 std::nullopt?
- 默认情况下,"std::shared_ptr"不应该使用"std::d efault_delete"吗?
- 推荐的方法在不初始化值的情况下使数组类型为 std::unique_ptr?
- 在运行时,何时完全初始化 std 库才能在不破坏代码的情况下使用它?
- 如何在没有迭代器的情况下使用 std::for_each + std::execution::p ar?
- 是否有可能在没有复制的情况下传递 std::vector<int> 作为参数来获得 std::vector<std::array<int, 3>>?
- std::regex 是否保证了最坏情况下的时间复杂度?