C++ 分配器在内存不足时使应用程序崩溃
c++ allocator crashes the application when not enough memory
当分配器由于内存有限而失败时。应用程序正在崩溃。抛出bad_alloc或返回 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;
}
}
new
运算符自行抛出bad_alloc
!所以使用try-catch
块:
pointer allocator<T>(size_type count) const
{
try
{
void* buffer = new (count * sizeof(T));
}
catch (bad_alloc& ba)
{
return nullptr; // or do whatever you have to do to recover
}
}
有关另一个示例,请参阅此处。
相关文章:
- 应用程序崩溃并显示"symbol _ZdlPvm, version Qt_5 not defined in file libQt5Core.so.5 with link time reference"
- 如何找出应用程序崩溃的原因 - Win 10 LTSB
- 操纵安卓相机的深度图导致应用程序崩溃
- 调用 java 的回调() 时应用程序崩溃.由于 detatchThread 而获得运行时错误
- QCompleter set模型使应用程序崩溃
- Qt 5 应用程序崩溃并出现"qLineEdit::setText"
- 切换NvAPI_Stereo_Deactivate/NvAPI_Stereo_activate会使unity应用程序崩溃
- eglSwapBuffers上的应用程序崩溃
- VLD 使应用程序崩溃
- 由于调用 std::condition_variable 后参数无效而导致应用程序崩溃
- 执行递归函数时 C++ 应用程序崩溃
- 在 C++/CLI/C# 项目中启用"Native Code Debugging"导致应用程序崩溃
- LOCAL_SHARED_LIBRARIES使我的应用程序崩溃
- 为什么使用 nullPtr 调用函数不会使我的应用程序崩溃
- 当删除上下文属性中的QLIST对象时,QT QML应用程序崩溃
- React 本机 0.59 应用程序崩溃并出现 libc 错误
- 当使用“制造”编译的程序中使用库时,应用程序崩溃
- 如何在导致应用程序崩溃的代码中修复指令
- C++多线程应用程序崩溃
- 当使用 /ENTRY:main 和 /MT 运行时库编译为 /SUBSYSTEM:WINDOWS 时,应用程序崩溃