C++ new運算符誤用之詳解

1. plain new/delete:

普通的new 定義如下:

void *operator new(std::size_t) throw(std::bad_alloc);

void operator delete(void*) throw();

注意:標準C++ plain new 失敗後拋出標準異常std::bad_alloc而非返回NULL,因此檢查返回值是否爲NULL判斷分配內存空間是沒有意義的

普通new申請空間示例代碼:


#include <iostream>
using namespace std;

typedef unsigned long ULONGS;
char *GetMemory(ULONGS size);

int main()
{
	try
	{
		ULONGS ulSize(10e11);
		char *pMem=GetMemory(ulSize);
		if(NULL == pMem)
		{
			cout<<"Alloc Memory failure!"<<endl;
		}
		delete [] pMem;
		pMem = NULL;

	}
	catch(const std::bad_alloc &ex)
	{
		cout<<ex.what()<<endl;
	}

	return 0;
}

char *GetMemory(ULONGS size)
{
	char * pMem = new char[size];//分配失敗,指針不爲空
	if(NULL == pMem)
	{
		cout<<"Alloc Memory failure!"<<endl;
	}
	return pMem;
}

這段代碼運行出來結果如下圖所示:



代碼拋出申請申請空間異常的信息



2.nothrow new/delete:


不拋出異常的運算符new的形式,new失敗時返回NULL定義如下:
void *operator new(std::size_t,const std::nothrow_t&) throw();

void operator delete(void*) throw();

struct nothrow_t{}; const nothrow_t nothrow;//nothrow作爲new的標誌性

將上面的代碼中申請內存空間函數稍作如下修改,其餘函數調用都不變

char *GetMemory(ULONGS size)
{
	char * pMem = new(nothrow) char[size];//分配失敗,指針爲空
	if(NULL == pMem)
	{
		cout<<"Alloc Memory failure!"<<endl;
	}
	return pMem;
}

運行該段程序,則運行結果顯示申請空間失敗後指針爲空,運行結果如下所示:






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章