在c代码中经常会见到这样的代码
char * str=(char *)malloc(100*sizeof(char));
if (str==NULL)
{
//错误处理
}
出于习惯的问题,在C++中也中也这么写
m_pToolBarDlg=new CDYToolBarDlg();
if (m_pToolBarDlg==NULL)
{
StringCchPrintf(szMsg,128,_T("new CDYToolBarDlg() failed in %s File at %d line "),_T(__FILE__),__LINE__);
MessageBox(szMsg,_T("Error"));
return -1;
}
这犯了一个极大的错误,因为在Visual C++ 6.0之后,new失败时候抛出一个异常(std::bad_alloc),而不是返回一个空指针。要解决这个问题有两种方式,一种是禁止抛出异常,一种是进行异常处理。禁止抛出异常又有两种方式。
@1:禁止抛出异常
@1.1 :用new (std::nothrow) T代替以前的new
m_pToolBarDlg=new(std::nothrow) CDYToolBarDlg();
if (m_pToolBarDlg==NULL)
{
StringCchPrintf(szMsg,128,_T("new CDYToolBarDlg() failed in %s File at %d line "),_T(__FILE__),__LINE__);
MessageBox(szMsg,_T("Error"));
return -1;
}
@1.2:项目链接到nothrownew.obj
@2:进行异常处理:
#include <new>
try
{
m_pToolBarDlg=new CDYToolBarDlg();
}
catch (const std::bad_alloc &)
{
StringCchPrintf(szMsg,128,_T("new CDYToolBarDlg() failed in %s File at %d line "),_T(__FILE__),__LINE__);
MessageBox(szMsg,_T("Error"));
return -1;
}
1:http://www.viva64.com/en/d/0293/print/
2:http://msdn.microsoft.com/en-us/library/kftdy56f%28v=vs.110%29.aspx
3:http://hi.baidu.com/widebright/item/e6a6c5f8d73145cf531c26c9