FMD开发文集 -- MFC调试模式下new操作符的特殊处理
作者:冯明德
一、在调试模式下,new操作符号通过宏定义转换成了调试版本。
(本文来源于图老师网站,更多请访问http://m.tulaoshi.com/cyuyanjiaocheng/)在文件头经常可以发现以下语句:
#ifdef _DEBUG#undef THIS_FILEstatic char THIS_FILE[]=__FILE__;#define new DEBUG_NEW#endif其中,将new定义为DEBUG_NEW
二、DEBUG_NEW的处理
调试版本的new操作函数:void* AFX_CDECL operator new(size_t nSize, LPCSTR lpszFileName, int nLine);
宏替换:#define DEBUG_NEW new(THIS_FILE, __LINE__) //文件名、行号被传入,供调试输出。
实际代码如下:
void* AFX_CDECL operator new(size_t nSize, LPCSTR lpszFileName, int nLine){return ::operator new(nSize, _NORMAL_BLOCK, lpszFileName, nLine);}//分配内存void* __cdecl operator new(size_t nSize, int nType, LPCSTR lpszFileName, int nLine){#ifdef _AFX_NO_DEBUG_CRTUNUSED_ALWAYS(nType);UNUSED_ALWAYS(lpszFileName);UNUSED_ALWAYS(nLine);return ::operator new(nSize);#elsevoid* pResult;#ifdef _AFXDLL_PNH pfnNewHandler = _pfnUninitialized;#endiffor (;;){pResult = _malloc_dbg(nSize, nType, lpszFileName, nLine);if (pResult != NULL)return pResult;#ifdef _AFXDLLif (pfnNewHandler == _pfnUninitialized){AFX_MODULE_THREAD_STATE* pState = AfxGetModuleThreadState();pfnNewHandler = pState-> m_pfnNewHandler;}if (pfnNewHandler == NULL || (*pfnNewHandler)(nSize) == 0)break;#elseif (_afxNewHandler == NULL || (*_afxNewHandler)(nSize) == 0)break;#endif}return pResult;#endif}#endif //_DEBUG(全文完)