我正在为家庭作业编写一个程序,我需要分配许多对象来检查位置和性能等方面的东西。我似乎无法捕捉到抛出的异常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;
}
}
};