Chinaunix首页 | 论坛 | 博客
  • 博客访问: 609687
  • 博文数量: 263
  • 博客积分: 6000
  • 博客等级: 准将
  • 技术积分: 2555
  • 用 户 组: 普通用户
  • 注册时间: 2008-02-26 11:20
文章分类

全部博文(263)

文章存档

2011年(10)

2010年(19)

2009年(170)

2008年(64)

我的朋友

分类: WINDOWS

2009-10-25 21:41:46

缘起:在阅读MFC框架应用程序时,在CPP源代码文件的开始都有如下的代码。想一探究竟,就在网上搜索,看见有人问类似的问题,将网友的帖子整理了一下,算是一个学习笔记,以便温习:

很笨#ifdef _DEBUG是什么意思?

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

在MFC中,可以使用DEBUG_NEW宏代替new 运算符来帮助定位内存泄漏。在程序的“Debug”版本中,DEBUG_NEW  将为所分配的每个对象跟踪文件名和行号。当编译程序的“Release”版本时,DEBUG_NEW  将解析为不包含文件名和行号信息的简单 new操作。因此,在程序的“Release”版本中不会造成任何速度损失。 
如果不想重写整个程序来使用  DEBUG_NEW 代替 new,则可以在源文件中定义下面的宏:   
#define  new  DEBUG_NEW 
当进行对象转储时,用  DEBUG_NEW  分配的每个对象均将显示被分配到的文件和行号,使您可以查明内存泄漏源。 
 
MFC  框架的“Debug”版本自动使用DEBUG_NEW,但代码不自动使用它。如果希望利用  DEBUG_NEW  的好处,则必须显式使用DEBUG_NEW  或#define  new,如上所示。 
__FILE__和__LINE__都是编译器定义的宏。当碰到__FILE__时,编译器会把__FILE__替换成一个字符串,这个字符串就是当前在编译的文件的路径名。在DEBUG_NEW的定义中没有直接使用__FILE__,而是用了THIS_FILE,其目的是为了减小目标文件的大小。假设在某个cpp文件中有100处使用了new,如果直接使用__FILE__,那编译器会产生100个常量字符串,这100个字符串都是这个cpp文件的路径名,显然十分冗余。如果使THIS_FILE,编译器只会产生一个常量字符串,那100处new的调用使用的都是指向常量字符串的指针。


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
阅读(535) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~