【发布时间】:2012-11-18 01:55:09
【问题描述】:
您好,这有点复杂,所以如果有任何不妥之处请告诉我,我们的团队正在编写一个 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 中得到了一堆链接器错误:
ex: libcmt.lib(malloc.obj) : error LNK2001: unresolved external symbol __imp_HeapAlloc
重新添加 operator new 的旧实现(不带附加参数)允许链接器成功链接所有内容。
我的问题:我希望 libcmt 看到我的宏(#define new new(FILE, FUNCSIG, LINE)),因此当它链接尝试链接我定义的版本(使用调试宏)。
我如何让它工作? (我也尝试使用 Visual Studio 中的属性表来定义宏)
【问题讨论】:
-
我认为该库不会链接,因为它不是用您重载的
new运算符编译的。仅仅在你自己的代码中定义一个重载的new不会神奇地让它出现在预构建的库中。 -
正如@dreamlax 所说,这行不通。这是 MFC 中的 Microsoft hack,应该取出并射击。如果在定义宏之后使用该关键字,则编写名称为关键字的宏会产生未定义的行为。
-
@PeteBecker 我更喜欢用老式的圣经用石头砸自己。
标签: c++ overloading new-operator