【发布时间】:2012-12-13 00:48:06
【问题描述】:
我正在为家庭作业编写一个程序,我需要分配许多对象来检查位置和性能等方面的内容。我似乎无法捕捉到new 引发的异常
#include "List.h"
#include<iostream>
#include <exception>
int main(int argc, char **argv) {
cout << "size of List c++ : " << sizeof(List) << endl; //16
List * ptrList = new List();
unsigned long var = 0;
try {
for (;; ++var) {
List * ptrList2 = new List();
ptrList->next = ptrList2;
ptrList2->previous = ptrList;
ptrList = ptrList2;
}
} catch (bad_alloc const& e) {
cout << "caught : " << e.what() << endl;
// } catch (...) { //this won't work either
}
结果:
此应用程序已请求运行时终止它 不寻常的方式。请联系应用程序的支持团队了解更多信息 信息。
如果我将分配部分更改为:
List * ptrList2 = new (nothrow) List();
if (!ptrList2) {
cout << "out of memory - created " << var << " nodes" << endl;
break;
}
我觉得不错:
out of memory - created 87921929 nodes
为什么我抓不到bad_alloc?
我在 Windows 7 x64 Pro 上使用 mingwin
C:\Users\MrD>g++ --version
g++ (GCC) 4.7.2
名单:
class List {
long j;
public:
List * next;
List * previous;
virtual long jj() {
return this->j;
}
List() {
next = previous = 0;
j = 0;
}
virtual ~List() {
if (next) {
next->previous = this->previous;
}
if (previous) {
previous->next = this->next;
}
}
};
【问题讨论】:
-
您可能没有足够的内存来处理异常。
-
@Chris:Wow - 从来没有想过 :) - 任何方式来告诉(虽然似乎很荒谬 - bad_alloc 抛出 bad_alloc ?)
-
我不确定。我之所以想到这一点,是因为我几天前在“为什么使用 nothrow 版本?”中看到了它。问题。
-
见en.cppreference.com/w/cpp/memory/new/set_new_handler,试试那里的例子。你也可以尝试在启动时分配一个缓冲区,然后在 new-handler 中释放它(并抛出),看看是否可能需要异常处理。
-
@Chris:我认为这不太可能。它通常被抛出并分配在堆栈上。
标签: c++ exception g++ mingw try-catch