ITPub博客

首页 > 应用开发 > IT综合 > C++ new 和异常

C++ new 和异常

原创 IT综合 作者:gaopengtttt 时间:2016-08-08 11:49:59 0 删除 编辑
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);
        }
}


更加简洁

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/7728585/viewspace-2123136/ ,如需转载,请注明出处,否则将追究法律责任。

下一篇: C++类和异常例子
请登录后发表评论 登录
全部评论
wxh gp_22389860 公众号 MySQL学习 书籍 深入理解MySQL主从原理

注册时间:2021-06-07

  • 博文量
    868
  • 访问量
    3495560