C++ new 和异常

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


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


int main(void)
{
        test *pd;
        try
        {
                cout<<"Will give big mem?!"<                 pd = new test[10000000];
        }
        catch (bad_alloc &ba)
        {
                cout<<"exception!\n";
                cout<                 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
#include
#include
using namespace std;




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




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


更加简洁
请使用浏览器的分享功能分享到微信等