C++ 如何在c++;?

C++ 如何在c++;?,c++,exception,try-catch,C++,Exception,Try Catch,谁能告诉我如何捕捉内存不足异常 例如 try { while(true) { int i = new int; } } catch( ? <--- what should be put here?) { //exception handling } 试试看 { while(true) { int i=新的int; } } 捕获(?catch(标准::错误分配和ba){ cerrCatch 您还需要一种处理错误的策略,因为您想做的许多事情都需

谁能告诉我如何捕捉内存不足异常

例如

try
{
    while(true)
    {
        int i = new int;
    }
}
catch( ? <--- what should be put here?)
{
    //exception handling
}
试试看
{
while(true)
{
int i=新的int;
}
}
捕获(?
catch(标准::错误分配和ba){
cerrCatch


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

您应该
捕获
类型为
std::bad\u alloc
的对象

或者,您也可以使用
nothrow
verison的
new
作为:

int *pi = new (nothrow) int[N]; 
if(pi == NULL) 
{
   std::cout << "Could not allocate memory" << std::endl;
}
int*pi=new(nothrow)int[N];
if(pi==NULL)
{

std::cout正如其他人所指出的,您想要捕获的是
std::bad_alloc
。您还可以使用
catch(…)
catch(exception&ex)
捕获任何异常;后者允许在异常处理程序中读取和使用异常数据

<> Mark Ransom已经指出,当程序不能分配更多的内存时,即使打印错误消息也可能失败。
#include <iostream>

using namespace std;

int main() {
    unsigned long long i = 0;
    try {
        while(true) {
            // Leaks memory on each iteration as there is no matching delete
            int* a = new int;
            i++;
        }
    } catch(bad_alloc& ex) {
        cerr << sizeof(int) * i << " bytes: Out of memory!";
        cin.get();
        exit(1);
    }

    return 0; // Unreachable
}

注意:打印到CERP可能由于内存不足而失败。@ BDONLAN:我同意您的观点。我没有考虑到这种情况,我太习惯于当我试图分配大量的向量时出现的问题。。我已经更新了我的答案。@bdonlan:在我发表评论后,速度非常慢:@MooingDuck的可能重复项我认为下面的答案比该问题的答案更能满足所有人的需要。我可以以某种方式将nothrow版本的new设置为默认值,所以我不需要编写
(nothrow)
每次?@Quest:我不知道这是否可行。也许,作为最后的手段,你可以这样做:
#定义新的(nothrow)
然后
int*pi=NEW int[N]
。我想我从来没有在我的代码中使用过这种形式的new,成功分配内存不是可选的。请注意,在实际情况下,堆栈展开可能已经释放了一些内存(例如销毁本地
std::string
变量)在抛出和捕获错误之间。通常,
std::bad_alloc
的处理程序将相当“在外部”这个程序,内存可以在一个很深的嵌套情况下运行。只是说,像打印错误信息之类的东西不一定要失败。听说过RAII吗?如果你正在做这样的软件工程,就不需要使用C++了。你可以用C.我见过人们声称,这个“窍门”。预分配内存会导致永远不会运行内存不足的情况。为什么要将std::bad_alloc作为值捕获?更新代码以通过引用捕获异常。但是,此代码故意避免RAII,因为它专门用于泄漏内存以进行演示。这就是他回答。
int *pi = new (nothrow) int[N]; 
if(pi == NULL) 
{
   std::cout << "Could not allocate memory" << std::endl;
}
#include <iostream>

using namespace std;

int main() {
    unsigned long long i = 0;
    try {
        while(true) {
            // Leaks memory on each iteration as there is no matching delete
            int* a = new int;
            i++;
        }
    } catch(bad_alloc& ex) {
        cerr << sizeof(int) * i << " bytes: Out of memory!";
        cin.get();
        exit(1);
    }

    return 0; // Unreachable
}
// Reserve 16K of memory that can be deleted just in case we run out of memory
char* _emergencyMemory = new char[16384];
// ...
try {
// ...
} catch(bad_alloc& ex) {
    // Delete the reserved memory so we can print an error message before exiting
    delete[] _emergencyMemory;

    cerr << sizeof(int) * i << " bytes: Out of memory!";
    cin.get();
    exit(1);
}
//...