C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了c – 无法在MinGW中捕获bad_alloc大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在为一个家庭作业编写一个程序,我需要分配许多对象来检查局部性和性能等等.我似乎无法捕捉到新的抛出的异常

#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;
        }
    }
};

解决方法

因为没有人自愿参加 I did it – 尤其是George Koehler对于某些gdb调试的回答 – 看来它毕竟是一个bug但我不会接受我的回答,直到这被证实 – 厌倦了等待.

大佬总结

以上是大佬教程为你收集整理的c – 无法在MinGW中捕获bad_alloc全部内容,希望文章能够帮你解决c – 无法在MinGW中捕获bad_alloc所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。