如何在c ++中捕获内存异常? [英] how to catch out of memory exception in c++?

查看:452
本文介绍了如何在c ++中捕获内存异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以告诉我如何捕获内存异常?



例如

  try 
{
while(true)
{
int i = new int;
}
}
catch(?&--- ---应该放在这里?)
{
//异常处理
} $ b $

 <$> 

c $ c> queue< int> q;
try
{
while(true)
{
q.push(10);
}
}
catch(?< ----这里应该放什么?)
{
//错误处理
}


解决方案

捕获 std :: bad_alloc



你还需要一个处理错误的策略,因为你想做的很多事情都需要内存(即使只是在关闭之前向用户显示一个错误)。一种策略是在启动时分配一块内存,并在尝试使用更多内存之前在异常处理程序 delete ,以便有一些可以使用。


can anyone please tell me how to catch out of memory exception?

for ex.

try
{
    while(true)
    {
        int i = new int;
    }
}
catch( ? <--- what should be put here?)
{
    //exception handling
}

and also this,

queue<int> q;
try
{
     while(true)
     {
          q.push(10);
     }
}
catch( ? <---- what should be put here?)
{
     //error handling
}

解决方案

Catch std::bad_alloc.

You will also need a strategy for handling the errors, since many of the things you'd like to do will require memory (even if it's only to display an error to the user before shutting down). One strategy is to allocate a block of memory at startup, and delete it in the exception handler before attempting to use more memory, so that there is some available to use.

这篇关于如何在c ++中捕获内存异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆