赞
踩
类型
下面的代码是参考自:http://blog.sina.com.cn/s/blog_3f56d7800100i1uf.html
/*
* =====================================================================================
*
* Filename: new_delete_trace.cpp
*
* Description:
*
* Version: 1.0
* Created: 08/22/2012 12:26:42 AM
* Revision: none
* Compiler: gcc
*
* Author: lsff (lsff),
* Organization:
*
* =====================================================================================
*/
#include <cstdlib>
#include <iostream>
using namespace std;
#define _DEBUG
#ifdef _DEBUG
void *operator new(size_t size, const char* file, int line)
{
cout<<"new size:"<<size<<endl;
cout<<file<<" "<<line<<endl;
// return mallloc(size);
return operator new(size);
}
void *operator new[](size_t size, const char* file, int line)
{
cout<<"new size:"<<size<<endl;
cout<<file<<" "<<line<<endl;
void *p = malloc(size);
cout<<reinterpret_cast<long>(p)<<endl;;
// return mallloc(size);
return p;
}
void operator delete(void *p)
{
long ip =reinterpret_cast<long>(p);
cout<<"delete "<<ip<<endl;
free(p);
}
void operator delete[](void *p)
{
cout<<"delte[]"<<reinterpret_cast<long>(p)<<endl;
free(p);
}
// 注意:上面连个函数体虽然相同,但一个都不能少
// delete[] 可以认为系统看到这个函数,就会循环地去调用该空间的
// 每个对象的析构函数再释放空间,但是delete 就只是调用第一个对象
// 的析构函数就释放空间,所以可以认为[] 区别了系统怎样去调用
// 底层的free,因为free 对数组和单个元素是不区分的,但是在free之前
// 系统通过[] 完成类似free的智能操作
void operator delete(void *p,const char*file ,int line)
{
cout<<"delete "<<file<<" "<<line<<endl;
free(p);
}
void operator delete[](void *p,const char*file ,int line)
{
cout<<"delete[] "<<file<<" "<<line<<endl;
free(p);
}
//上面两个函数是有用的,在异常发生的时候,默默无闻啊~~~
#define new new(__FILE__, __LINE__)
#endif
class test
{
private:
int ival;
public:
test(){
throw int(3);
}
~test()
{
cout<<__FUNCTION__<<endl;
}
};
int main()
{
// int *p=new int[5];
// delete (p);
// test *pc = new test[5];
// delete []pc; // pc是指向对象的数组时必须使用delete[],这样才会以此调用构造函数
try{
test *pc = new test;
delete pc;
}
catch(int a)
{
}
return 0;
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。