Override new operator in C++ while crtdbg.h is causing conflicts

后端 未结 4 411
独厮守ぢ
独厮守ぢ 2021-02-02 04:48

While trying out some memory tracking and preparation for my own memory manager, I tried to override the new operator. The article on flipcode was my main guideline in this proc

4条回答
  •  佛祖请我去吃肉
    2021-02-02 05:15

    Allright, the way I solved it for now, without having to use a custom 'new' define is that I've made a generic header file, let's say 'Engine.h' that is included in every file. This can be enforced by using the Forced Include File in the Project Settings / Configuration Properties / C/C++ / Advanced.

    This file contains the #define (removed from the memdebug.h)

    engine.h

    #define _CRTDBG_MAP_ALLOC
    #include 
    #include 
    
    #include 
    
    #include "MemoryNappy.h"
    
    #define DEBUG_NEW new(__FILE__, __LINE__)
    #define new DEBUG_NEW
    

    This enforces the system to consider the crtdbg.h before the custom new-define and won't be changing the new there. The second time it's included somewhere down the line, it's just using the data that has already been loaded before. (In the case of including after the include of "engine.h").

    Please note that overriding the new operator is still risky business when using third party libraries that might do the same trick. This causes the new operator for those files to be rewritten using the pattern used here. In that case you might want to reconsider the usage of a custom new define as in this fragment:

    #define myNew new(__FILE__, __LINE__)
    

    (Also described in http://www.flipcode.com/archives/Detecting_Memory_Leaks.shtml)

提交回复
热议问题