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:
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:
如果定义了_DEBUG宏
把代码中的new用DEBUG_NEW替换
取消THIS_FILE宏定义
定义THIS_FILE[]变量并初始化为__FILE__值
定义结束
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
就起作用了
代码中一般这样写:
#ifdef new
xxxxx
#else
xxxxx
#endif
这个在调试的时候很有用。
代码中一般这样写:
#ifdef new
xxxxx
#else
xxxxx
#endif
这个在调试的时候很有用。
你可以在:点击工程名-右键选择C/C++-预处理:
预处理定义。。
里面就有类似:WIN32;_WINDOWS;_DEBUG;_USRDLL
的东西
如果不想重写整个程序来使用 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的调用使用的都是指向常量字符串的指针。
如果定义了_DEBUG宏
把代码中的new用DEBUG_NEW替换
取消THIS_FILE宏定义
定义THIS_FILE[]变量并初始化为__FILE__值
定义结束