VC里的#define new DEBUG_NEW
以下代碼常常在一個(gè)類文件的開頭出現(xiàn),是什么意思呢?
#ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif先看MSDN里的解釋:
Remarks
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.
?
? ? 這樣就很清楚了,當(dāng)在debug模式下時(shí),我們分配內(nèi)存時(shí)的new被替換成DEBUG_NEW,而這個(gè)DEBUG_NEW不僅要傳入內(nèi)存塊的大小,還要傳入源文件名和行號(hào),這就有個(gè)好處,即當(dāng)發(fā)生內(nèi)存泄漏時(shí),我們可以在調(diào)試模式下定位到該問(wèn)題代碼處。若刪掉該句,就不能進(jìn)行定位了。而在release版本下的new就是簡(jiǎn)單的new,并不會(huì)傳入文件名和行號(hào)。
? ? 如果定義了_DEBUG,表示在調(diào)試狀態(tài)下編譯,因此相應(yīng)修改了兩個(gè)符號(hào)的定義THIS_FILE是一個(gè)char數(shù)組全局變量,字符串值為當(dāng)前文件的全路徑,這樣在Debug版本中當(dāng)程序出錯(cuò)時(shí)出錯(cuò)處理代碼可用這個(gè)變量告訴你是哪個(gè)文件中的代碼有問(wèn)題。
轉(zhuǎn)載于:https://www.cnblogs.com/imapla/archive/2012/09/03/2668859.html
總結(jié)
以上是生活随笔為你收集整理的VC里的#define new DEBUG_NEW的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: POJ1724 ROADS 费用最短路
- 下一篇: c++对象的内存布局2--进阶篇---C