52ky 发表于 2022-5-2 10:54:42

DEBUG_NEW和THIS_FILE

C++ 比较晦涩的特性之一是可以重载 new 运算符,甚至可以将参数附加到它。 通常, operator new 只接受要分配的对象的大小:
       void* operator new(size_t nAlloc)
      {
            return malloc(nAlloc);
      }
但是,您也可以使用所需的任何其他参数重载 new 运算符,只要在调用 new 时提供这些参数即可。 在各种 App Wizards 中,这就是 MFC 所做的。 典型的 MFC 程序 (.cpp) 文件在顶部有以下几行,通常由 AppWizard 生成:
       #ifdef _DEBUG
      #define new DEBUG_NEW
      #undef THIS_FILE
      static char THIS_FILE[] = __FILE__;
      #endif

MFC 将 new 重定义为 DEBUG_NEW。但 DEBUG_NEW 是什么? afx.h 道出了原委:

      // (simplified)
      #ifdef _DEBUG
      # define DEBUG_NEW new(THIS_FILE, __LINE__)
      #else
      # define DEBUG_NEW new
      #endif
在 debug 生成模式中,MFC 重载了操作符 new 以获取两个额外的参数,比如:
      void* operator new(size_t nSize,
      LPCSTR lpszFileName, int nLine);
  重载的版本与普通的 new 同样都有表示对象大小的 size 参数,但还增加了两个参数:源文件名称和行数。因此,无论何时,只要你写:
      pfoo = new CFoo(..);
预处理程序便会将它转变为:
      pfoo = new (sizeof(CFoo), THIS_FILE, __LINE__) CFoo(...);
  __FILE__(用来初始化 THIS_FILE)和 __LINE__ 是专用的预处理符号,它保存当前被编译的模块文件名称和行数。 其主要用途是当你的应用程序泄漏时,MFC 能显示一个消息。如:
      Shame on you! You didn''t free the CFoo object in foo.cpp, line 127!
  这对于调试来说,是个巨大的福音。

(One of the more obscure features of C + + is that it can overload the new operator and even attach parameters to it. Generally, operator new only accepts the size of the object to be allocated:
void* operator new(size_t nAlloc)
{
return malloc(nAlloc);
}
However, you can also overload the new operator with any other parameters you need, as long as you supply them when you call new. In various app wizards, this is what MFC does. A typical MFC program (. CPP) file has the following lines at the top, which are usually generated by the AppWizard:
#ifdef _ DEBUG
#define new DEBUG_ NEW
#undef THIS_ FILE
static char THIS_ FILE[] = __ FILE__;
#endif
MFC redefines new as debug_ NEW。 But debug_ What is new? afx. H tells the whole story:
// (simplified)
#ifdef _ DEBUG
# define DEBUG_ NEW new(THIS_FILE, __LINE__)
#else
# define DEBUG_ NEW new
#endif
In the debug generation mode, MFC overloads the operator new to obtain two additional parameters, such as:
void* operator new(size_t nSize,
LPCSTR lpszFileName, int nLine);
The overloaded version has the same size parameter indicating the size of the object as the ordinary new, but two parameters are added: the name of the source file and the number of lines. So whenever you write:
pfoo = new CFoo(..);
The preprocessor turns it into:
pfoo = new (sizeof(CFoo), THIS_ FILE, __ LINE__)CFoo(...);
__ FILE__ (used to initialize this_file) and__ LINE__Is a special preprocessing symbol, which saves the name and number of lines of the currently compiled module file. Its main purpose is that MFC can display a message when your application leaks. For example:
Shame on you!You didn''t free the CFoo object in foo. cpp, line 127!
This is a great blessing for debugging.
)



页: [1]
查看完整版本: DEBUG_NEW和THIS_FILE