c++ - c++分配器在内存不足时使应用程序崩溃
问题描述
当分配器由于内存有限而失败时。该应用程序正在崩溃。抛出bad_alloc或 return nullptr不会停止崩溃。有人知道吗?
pointer allocator<T>(size_type count) const
{
void* buffer = new (count * sizeof(T));
if (!buffer) // if buffer == nullptr crashes app
throw bad_alloc; // doing this crashes app
/* or alternatively
* try {
* void* buffer = new (count * sizeof(T));
* } catch (const std::exception& e) {
* std::cerr << "failed to allocate " << count << std::endl;
* return nullptr;
* }
*/
}
那么如何优雅地关闭应用并说内存不足呢?
解决方案
有很多事情需要不传播异常,标准通过指定std::terminate
如果异常会逃逸则调用它来做到这一点。
如果没有您程序其余部分的上下文,我们无法知道它是其中之一,还是只是一个异常离开main
。
对后者的修复可能看起来像
int main()
{
try
{
// whatever here
}
catch (std::exception & e)
{
std::cerr << e.what();
return EXIT_FAILURE;
}
}
推荐阅读
- kotlin - 为什么过滤掉空映射键不会在 kotlin 中将类型更改为不可空?
- c++ - 地图内的 C++ 多个地图
- javascript - 子 JavaScript 类如何引用父类中的属性?
- python - 如何测试异步流(协程、任务)?
- python - PySpark 在时间戳上使用 Min 函数选择错误的值
- pandas - 如何从此数据框中删除一行?
- java - java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“boolean java.lang.String.isEmpty()”
- sql-server - 如何知道当前有多少用户连接到 SQL Server
- python-2.7 - RawPy - 确定 ARW(原始传感器)图像的过滤器阵列/图像类型是否为“Bayer”
- spring - 使用 Spring Boot 的 Web API 通知