VC里的"#define new DEBUG_NEW"

来源:互联网 发布:佛山市2015年经济数据 编辑:程序博客网 时间:2024/06/05 00:50

转载地址:http://www.cnblogs.com/imapla/archive/2012/09/03/2668859.html

以下代码常常在一个类文件的开头出现,是什么意思呢?

#ifdef _DEBUG#define new DEBUG_NEW#undef THIS_FILEstatic 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.

 

     这样就很清楚了,当在debug模式下时,我们分配内存时的new被替换成DEBUG_NEW,而这个DEBUG_NEW不仅要传入内存块的大小,还要传入源文件名和行号,这就有个好处,即当发生内存泄漏时,我们可以在调试模式下定位到该问题代码处。若删掉该句,就不能进行定位了。而在release版本下的new就是简单的new,并不会传入文件名和行号。
     如果定义了_DEBUG,表示在调试状态下编译,因此相应修改了两个符号的定义THIS_FILE是一个char数组全局变量,字符串值为当前文件的全路径,这样在Debug版本中当程序出错时出错处理代码可用这个变量告诉你是哪个文件中的代码有问题。


转载地址:http://li-bonan.blog.163.com/blog/static/13556477020107219031551/

#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 的6个宏之一。#define new DEBUG_NEW 
DEBUG_NEW定位内存泄露并且跟踪文件名.

__FILE__和__LINE__都是编译器定义的宏。当碰到__FILE__时,编译器会把__FILE__替换成一个字符串,这个字符串就是当前在编译的文件的路径名。在DEBUG_NEW的定义中没有直接使用__FILE__,而是用了THIS_FILE,其目的是为了减小目标文件的大小。假设在某个cpp文件中有100处使用了new,如果直接使用__FILE__,那编译器会产生100个常量字符串,这100个字符串都是这个cpp文件的路径名,显然十分冗余。如果使用THIS_FILE,编译器只会产生一个常量字符串,那100处new的调用使用的都是指向常量字符串的指针。


因为THIS_FILE是一个字符串指针,所以可以使用下面函数来参看文件路径:
MessageBox(THIS_FILE);

原创粉丝点击