1

嗨,这有点复杂,所以如果其中任何一个没有意义,请告诉我,我们的团队正在编写一个 C++ 应用程序,我们之前已经重载了 operator new。最近我遇到了这篇文章:http ://www.flipcode.com/archives/How_To_Find_Memory_Leaks.shtml关于如何通过我们的内存分配获取调试信息。

应用程序中的所有文件#include 一个我们有编译时平台配置的文件,在该文件中我添加了以下内容:

#ifdef _DEBUG
void* operator new(size_t size, const char *filename, const char *funcname, int line);
void* operator new[](size_t size, const char *filename, const char *funcname, int line);
#define new new(__FILE__, __FUNCSIG__, __LINE__)
#endif

由于我们只为我们的平台构建链接 libcmt.lib,为了使用 STL,我删除了我们旧的 operator new 实现,它看起来像:

// in a .cpp file:
void*
operator new(size_t size) { ... }

并将其替换为:

// in the same .cpp file as above...
#undef new
void* operator new(size_t size, const char *filename, const char *funcname, int line) { ... }
#define new new(__FILE__, __FUNCSIG__, __LINE__)

这适用于编译,但我从 libcmt.lib 得到一堆链接器错误:

例如:libcmt.lib(malloc.obj):错误 LNK2001:未解析的外部符号 __imp_HeapAlloc

添加回 operator new 的旧实现(没有附加参数)允许链接器成功链接所有内容。

我的问题:我希望 libcmt 看到我的宏(#define new new( FILE , FUNCSIG , LINE )),因此当它链接时尝试链接我定义的版本(使用调试宏)。

我怎样才能让它工作?(我还尝试使用 Visual Studio 中的属性表来定义宏)

4

1 回答 1

4

你不能让它工作。如果在任何包含标准头的文件中定义了此宏,则行为未定义。当然,项目的正常发展将导致人们定义类 local operator new,或使用放置新,或该宏将破坏的多种技术中的任何一种。它与#define while if. 即使您不使用标准库,在宏中重新定义关键字也肯定会遇到麻烦。

于 2012-11-29T21:50:13.937 回答