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


更加简洁
上一篇:线程的上锁和睡眠


下一篇:C++异常处理与临时副本