Posted on 2010-08-11 16:02
幻海藍夢 閱讀(6624)
評論(0) 編輯 收藏 所屬分類:
C++
原文:http://hi.baidu.com/medici888/blog/item/022a43554bdfa2c8b745ae8b.html
1
#ifdef _DEBUG
virtual void AssertValid() const; //assert(斷言)valid(有效的,正確的)
virtual void Dump(CDumpContext& dc) const; //存儲上下文
#endif
這兩個函數是調試用的,第一個函數檢查可用性,即是否有效
第二個函數如果未更改的話,最終調用的是Cwnd::Dump();
輸出窗口類名,標題名等一系列信息(在輸出窗口中)
#ifdef _DEBUG
#endif
這是條件編譯,即如果有#define _DEBUG這兩個函數會編譯,否則忽略,
當你用debug生成時(相對于release)開發環境則自動的加上這個宏定義,這兩個函數有效。
2
#ifdef _DEBUG // 判斷是否定義_DEBUG
#undef THIS_FILE // 取消THIS_FILE的定義
static char THIS_FILE[]=__FILE__; // 定義THIS_FILE指向文件名
#define new DEBUG_NEW // 定義調試new宏,取代new關鍵字
#endif // 結束
如果定義了_DEBUG,表示在調試狀態下編譯,因此相應修改了兩個符號的定義
THIS_FILE是一個char數組全局變量,字符串值為當前文件的全路徑,這樣在Debug版本中當程序出錯時出錯處理代碼可用這個變量告訴你是哪個文件中的代碼有問題。
定義 _DEBUG后,由于定義了_DEBUG,編譯器確定這是一個調試,編譯#ifdef _DEBUG和#endif之間的代碼。#undef 表示清除當前定義的宏,使得THIS_FILE無定義。__FILE__ 是編譯器能識別的事先定義的ANSI C 的6個宏之一。#define new DEBUG_NEW
DEBUG_NEW定位內存泄露并且跟蹤文件名.
////////////////////////////////////////////////////////////////////////
///另一種解釋
#ifdef _DEBUG //如果是debug狀態
#undef THIS_FILE //清除THIS_FILE
static char THIS_FILE[]=__FILE__; //定義THIS_FILE為 //__FILE__(這是當前文件全路徑名字)
#define new DEBUG_NEW //定義new為DEBUG_NEW(這個可以檢測到內存泄露之類的問題,其實就是可以使用crt開頭的那幾個調試函數)
#endif
在用vc時,利用AppWizard會產生如下代碼:
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
對于
#define new DEBUG_NEW
首先看msdn的解釋:
Assists in finding memory leaks. You can use DEBUG_NEW everywhere in your program that you would ordinarily use the new operator to allocate heap storage.
In debug mode (when the _DEBUG symbol is defined), DEBUG_NEW keeps track of the filename and line number for each object that it allocates. Then, when you use the CMemoryState::DumpAllObjectsSince member function, each object allocated with DEBUG_NEW is shown with the filename and line number where it was allocated.
To use DEBUG_NEW, insert the following directive into your source files:
#define new DEBUG_NEW
Once you insert this directive, the preprocessor will insert DEBUG_NEW wherever you use new, and MFC does the rest. When you compile a release version of your program, DEBUG_NEW resolves to a simple new operation, and the filename and line number information is not generated.
再查看定義:
#ifdef _DEBUG
void* AFX_CDECL operator new(size_t nSize, LPCSTR lpszFileName, int nLine);
#define DEBUG_NEW new(THIS_FILE, __LINE__)
#else
#define DEBUG_NEW new
#endif
這樣就很清楚了,當在debug模式下時,我們分配內存時的new被替換成DEBUG_NEW,而這個DEBUG_NEW不僅要傳入內存塊的大小,還要傳入源文件名和行號,這就有個好處,即當發生內存泄漏時,我們可以在調試模式下定位到該問題代碼處。若刪掉該句,就不能進行定位了。而在release版本下的new就是簡單的new,并不會傳入文件名和行號。
因此,我們在開發代碼階段,保留上述代碼是值得的。