WINX 庫的 AutoFreeAlloc 與 STD_NEW(基於 placement new)深受開發者好評。但在 MFC 專案中引入 WINX 時,常遇到編譯錯誤:STD_NEW 中的 placement new 與 MFC 的 DEBUG_NEW 宏衝突。
MFC 在 Debug 模式下,於每個 .cpp 文件頂部自動生成:
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
這將全局 new 替換為 DEBUG_NEW,以追蹤內存洩漏(記錄文件/行號)。
STD_NEW 使用標準 C++ placement new:new (ptr) Type(args)#define new DEBUG_NEW 將其展開為 DEBUG_NEW (ptr) Type(args)DEBUG_NEW 不接受額外參數 → 編譯失敗這是 MFC 宏污染全局命名空間的經典副作用。
在需要使用 STD_NEW 的 .cpp 文件中,刪除或註釋掉:
// #define new DEBUG_NEW
副作用:該文件內的普通 new 將不再被 MFC 內存洩漏檢測追蹤。
保留 MFC 宏,但將文件中所有動態分配改為顯式調用:
// 原代碼
Type* a = new Type(arg1, arg2);
// 修改為
Type* a = DEBUG_NEW Type(arg1, arg2);
這樣:
DEBUG_NEW 正確展開,保留內存洩漏追蹤STD_NEW 內部的 placement new 不受影響(因不匹配宏模式)全項目統一採用
DEBUG_NEW替代裸new,不僅解決 WINX 兼容,更能確保所有動態分配均納入 MFC 診斷體系。
new Type( → DEBUG_NEW Type(new Type[n] → DEBUG_NEW Type[n]_CRTDBG_MAP_ALLOC 可進一步定位 CRT 堆分配洩漏#define new DEBUG_NEW 污染 placement new 語法DEBUG_NEW 才是正統之道這也是現代 C++ 開發中「顯式優於隱式」原則的生動體現。