0

谁能告诉我如何bad_alloc在 C++ 中模拟和产生异常?在某些地方的代码中,我正在使用new将引发bad_alloc异常的运算符。我想模拟这种情况,需要测试代码。

4

1 回答 1

1

巴拉穆鲁甘,

今天下午我也有同样的疑问,在这里没有看到任何相关的东西。所以我去了 CPlusPlus并将 try catch 放入一个无限循环中,并且工作。在 VS C++ 2010 Express 下。

在我的代码下面:

// bad_alloc standard exception
#include <iostream>
#include <exception>
using namespace std;

int main () 
{
  unsigned int count=0;
  while (1) 
  {
    count++;
    try
     {
      int* myarray= new int[1000000];
     }
     catch (exception& e)
     {
    cout << "Standard exception: " << e.what() << endl;
    cout << "\nAborting after "<< count << " loops";
    return -1;
     }
   }
cout<<"\nNormal finishing...";
return 0;
}

就我而言,它在 523 次循环后被捕获。如果我知道将堆限制为财政记忆的设置,我会更好,如果我发现我会让你知道。

于 2013-04-23T22:19:41.993 回答