#include <new>
#include <cstdio>
#include <cstdlib>
#include<iostream>
using namespace std;
void* operator new(size_t size)
{
std::cout<<"operator new:"<<size<<" Byte"<<endl;
void* m= malloc(size);
if(!m)
cout<<"out of memory"<<endl;
return m;
}
void operator delete(void* m)
{
cout<<"operator delete"<<endl;
free(m);
}
void operator delete[](void* m)
{
cout<<"operator delete"<<endl;
free(m);
}
class S{
int s[1000000];
public:
S() {
cout<<"S::S()"<<endl;
}
~S() {
cout<<"S::~S()"<<endl;
}
};
int main(int argc, char* argv[])
{
int* p = new int[5];
delete []p;
cout<<endl;
S* s = new S;
delete s;
cout<<endl;
while(true)
{
S* sa = new S[30];
delete []sa;
}
return 0;
}
通过重写new delete可以检测内存泄露。
重载的delete [] 有点奇怪,但是的确是对的,不会造成内存泄露。