C++中new失败的三种处理方式

8月 21st, 2012
Visited 9502 times, 16 so far today
0

Comments

                    如果对象动态的申请内存的时候或调用相应的构造函数来生成对象的时候,而计算机中内存又不够用怎么办?我们第一感觉想到的就是new异常处理啊,对! 我们可以用bad_alloc异常类来抛出new失败的异常,并在catch(bad_alloc &)异常处理器中处理。其实C++中存在有三种new失败的策略。

1.应用标准的异常类来处理(c++中推荐的处理方式)

代码示例:

#include <iostream>
#include <new>//new运算符的头文件定义
using namespace std;

int main(){
double *doublePtr[50];//声明50个double指针类型
try{
for(int i = 0; i < 50; i++){
doublePtr[i] = new double[50000000];//每个double指针指向含有5000000个double元素的数组
cout<<“doublePtr[“<<i<<“]”<<” Allocation 50000000 double Memory!!!”<<endl;
}
}catch(bad_alloc &memoryAllocationException){
cout<<“In Exception occurred : “<<memoryAllocationException.what()<<endl;//打印异常信息
}
}

执行结果:

doublePtr[0] Allocation 50000000 double Memory!!!
doublePtr[1] Allocation 50000000 double Memory!!!
doublePtr[2] Allocation 50000000 double Memory!!!
doublePtr[3] Allocation 50000000 double Memory!!!
In Exception occurred : bad allocation

 

2.继承自C语言的方面的处理方式:

代码示例:

#include <iostream>
#include <new>//new运算符的头文件定义
using namespace std;

int main(){
double *doublePtr[50];//声明50个double指针类型
for(int i = 0; i < 50; i++){
doublePtr[i] = new(nothrow) double[50000000];//运行时并不抛出相应的异常,如果失败doublePtr[i]就会被赋值0
if(doublePtr[i]  ! = 0){//判断申请内存是否成功
cout<<“doublePtr[“<<i<<“]”<<” Allocation 50000000 double Memory!!!”<<endl;
}else{

cout<<“allocation memory Failure!!!”<<endl;//打印没有成功的情况
}
}

执行结果:

doublePtr[0] Allocation 50000000 double Memory!!!
doublePtr[1] Allocation 50000000 double Memory!!!
doublePtr[2] Allocation 50000000 double Memory!!!
doublePtr[3] Allocation 50000000 double Memory!!!
allocation memory Failure!!!
allocation memory Failure!!!
allocation memory Failure!!!
………下面省略循环50次的结果

 

3.指定相应的new失败处理函数:            //如果没有指定则抛出相应标准异常

示例代码:

#include <iostream>
#include <new>//new运算符的头文件定义
using namespace std;

void customeHandNew(){
cout<<“your new Double[] failture!!!”<<endl;
abort();//调用相应的停止程序
}

int main(){

//如何对于 没有指定new处理函数,C++还是会抛出相应的异常
set_new_handler(customeHandNew);//函数指针指定如果出现new失败情况时,调用指定的处理函数
double *doublePtr[50];//声明50个double指针类型
try{
for(int i = 0; i < 50; i++){
doublePtr[i] = new double[50000000];//每个double指针指向含有5000000double元素的数组
cout<<“doublePtr[“<<i<<“]”<<” Allocation 50000000 double Memory!!!”<<endl;
}
}catch(bad_alloc &memoryAllocationException){
cout<<“In Exception occurred : “<<memoryAllocationException.what()<<endl;//打印相应异常信息
}
}

执行结果:

doublePtr[0] Allocation 50000000 double Memory!!!
doublePtr[1] Allocation 50000000 double Memory!!!
doublePtr[2] Allocation 50000000 double Memory!!!
doublePtr[3] Allocation 50000000 double Memory!!!
your new Double[] failture!!!   //自定义的new处理函数,如果没有定义set_new_hander,则抛出标准异常