C++中基于Crt的内存泄露检测
作者:网络转载 发布时间:[ 2013/3/6 13:07:08 ] 推荐标签:
(6)因为STL里map内的tree用到了placement new, 所以如果你这样用会编译失败:
#ifdef _DEBUG
#define DEBUG_CLIENTBLOCK new( _CLIENT_BLOCK, __FILE__, __LINE__)
#else
#define DEBUG_CLIENTBLOCK
#endif
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#ifdef _DEBUG
#define new DEBUG_CLIENTBLOCK
#endif
#include <map>
你应该把 #include <map>放到宏定义的前面。
(7)如果你在宏 #define new DEBUG_CLIENTBLOCK 之后再声明或定义 operator new函数,都会因为宏替代而编译失败。
而STL的xdebug文件恰恰申明了operator new函数,所以请确保new的替代宏放在所有include头文件的后,尤其要放在STL头文件的后面。
//MyClass.cpp
#include "myclass.h"
#include <map>
#include <algorithm>
#ifdef _DEBUG
#define new DEBUG_CLIENTBLOCK
#endif
MyClass::MyClass()
{
char* p = new char('a');
}
(8)如果你觉得上面的这种new替代宏分散在各个CPP里太麻烦,想把所有的东西放到一个通用头文件里,请参考下面定义的方式:
//MemLeakChecker.h
#include <map>
#include <algorithm>
//other STL file
#ifdef _DEBUG
#define DEBUG_CLIENTBLOCK new( _CLIENT_BLOCK, __FILE__, __LINE__)
#else
#define DEBUG_CLIENTBLOCK
#endif
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#ifdef _DEBUG
#define new DEBUG_CLIENTBLOCK
#endif

sales@spasvo.com