C++ new 和异常

new异常,在分配内存的时候如果失败我们可以使用bad_alloc类来完成他在new头文件中,
他是从exception类共有派生而来,当无法分配内存给予new一个空指针,使用bad_alloc的
what()来返回输出
异常如下
#includ<iostream>
#include<new>      //必须包含
#include<cstdlib>
using namespace std;


class test
{
        public:
                double a[20000];
                ~test(void){cout<<"test"<<endl;}
};


int main(void)
{
        test *pd;
        try
        {
                cout<<"Will give big mem?!"<<endl;
                pd = new test[10000000];
        }
        catch (bad_alloc &ba)
        {
                cout<<"exception!\n";
                cout<<ba.what()<<endl;
                exit(EXIT_FAILURE);
        }
        cout<<"mem success\n";
        delete [] pd;
}


返回如下:
gaopeng@bogon:~/CPLUSPLUS/part15$ ./a.out 
Will give big mem?!
exception!
std::bad_alloc


另外在gcc中我们也可以这样用使用std::nothrow让分配内存失败返回一个空指针
#include<iostream>
#include<new>
#include<cstdlib>
using namespace std;




class test
{
        public:
                double a[20000];
                ~test(void){cout<<"test"<<endl;}
};




int main(void)
{
        test *pd;
        pd = new (std::nothrow)test[10000000];
        if(pd == 0)
        {
                cout<<"no mem give!!"<<endl;
                exit(EXIT_FAILURE);
        }
}


更加简洁
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值