行与不行,就凭我这水平,说出来未免显示太过自大。不还,我还想根据自己的代码来讨论这个问题。
重载operator new来检测内存只的办法,那就是在new的时候记录指针地址及文件名、行号,在delete的时候取消记录。到最后程序结束,还有哪些指针未释放,则为泄漏。
第一步,你得重载operator new,或者也可以重写。在http://www.cplusplus.com/reference/new/operator%20new/中指明new有三种形式,因为我们还分配数组,故还有new[]这个函数也要重载。那么有6种。原文中指明“The allocating versions ((1) and (2)) are also replaceable:”,则说明我们只能重载4个函数(也必须,不然检测不到部分内存分配,没有意义)。由于placement new不会有内存泄漏,也不能重载,可以不管。
#include <iostream> #include <cstdlib> using namespace std; inline void *operator new[](std::size_t size, const char *file, int line) { std::cout << "memory allocate at " << file << " line " << line << std::endl; void *p = ::operator new(size);// operator new (size,std::nothrow) return p; } inline void * operator new(std::size_t size, const char *file, int line) { std::cout << "memory allocate at " << file << " line " << line << std::endl; void *p = ::operator new(size); return p; } inline void operator delete(void *p) { std::cout << "free" << std::endl; free(p); } inline void operator delete[] (void *p) { std::cout << "free[]" << std::endl; free(p); } #define new new(__FILE__, __LINE__) class TTest { public: TTest(){ std::cout << "construct...." << std::endl; } ~TTest(){ std::cout << "destruct...." << std::endl; } }; int main() { TTest *p = new TTest(); delete p; return 0; }