他是从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?!"<
}
catch (bad_alloc &ba)
{
cout<<"exception!\n";
cout<
}
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!!"<
}
}
更加简洁