c++ overload operator new delete,

僤鯓⒐⒋嵵緔 提交于 2019-12-11 10:00:02

问题


Hi this is a little complicated so please let me know if any of this does not make sense, our team is writing a C++ application and we have previously had operator new overloaded. Recently I ran into this article: http://www.flipcode.com/archives/How_To_Find_Memory_Leaks.shtml about how to get debug information with our memory allocations.

All the files within the application #include one file where we have compile-time platform configurations, and within that file I added the following:

#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

Since we only link libcmt.lib for our platform build, to use the STL I removed our old implementation of operator new which looked like:

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

and replaced it with:

// 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__)

this works fine for compiling, but I'm getting a bunch of linker errors from libcmt.lib:

ex: libcmt.lib(malloc.obj) : error LNK2001: unresolved external symbol __imp_HeapAlloc

Adding back the old implementation of operator new (without the additional parameters) allows the linker to link everything successfully.

My question: I want libcmt to see my macro (#define new new(FILE, FUNCSIG, LINE)) and thus when it links try and link the version I defined (with the debug macros).

How do I get this to work?? (I also tried using the property sheets within visual studio to define the macro)


回答1:


You can't get it to work. If this macro is defined in any file that includes a standard header, the behavior is undefined. And of course, normal evolution of a project will lead people to define class local operator new, or use placement new, or any one of a number of techniques which this macro will break. It's on about the same level as #define while if. Redefining a keyword in a macro is a sure way of getting into trouble, even if you don't use the standard library.



来源:https://stackoverflow.com/questions/13635157/c-overload-operator-new-delete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!