new的异常处理

c++new运算符,如果分配内存失败了,不会像malloc一样返回NULL指针,所以判断返回NULL指针的方式判断内存分配是不合适的。

另外,有些网上说new分配内存分配的实际是自有内存,并不一定像malloc严格是堆内存,也可能是栈内存(存疑,因为测试的都跟堆内存紧挨着)

new分配的内存处理,抛出std::bad_alloc异常

#include <iostream>
#include <malloc.h>

#include <stdlib.h>
using namespace std;
/*void* operator new(size_t size)//全局重载new,已注释,存疑
{
   cout<<"global new\n";
   return malloc(size);
}
class A{//重载new成员函数,已注释,存疑
	private:
		int i;
	public:
		void *operator new(size_t size){
			cout<<"here,reload"<<endl;
			return ::operator new(size);
		}
}; */

int main(){
	try{
		double *p=new double[1000000000000000000];
		if(p==0) cout<<"NULL\n";
		cout<<"new"<<endl;
	}
	catch( std::bad_alloc &ex){
		cout<<"catch"<<endl;
		cout<<ex.what()<<endl;
	}
	
	
	
} 

猜你喜欢

转载自blog.csdn.net/zhangzhi2ma/article/details/82503294