#include<iostream>
using namespace std;
new_handler g_new_handler_f = NULL;
class A
{
public:
A(){ std::cout << "constructor" << std::endl; /* throw int();*/}
~A(){ std::cout << "destructor" << std::endl; }
};
new_handler set_new_handler_f(new_handler new_f)
{
new_handler p = g_new_handler_f;
g_new_handler_f = new_f;
return p;
}
void new_handler_f()
{
std::cout << "new_handler_f" << std::endl;
}
//new的一个可能的实现
void* operator new(size_t size)
{
std::cout << "void* operator new(size_t size)" << std::endl;
if (size == 0)
size = 1; // 这里保证像 new T[0] 这样得语句也是可行的
void *p = NULL;
while (!(p = malloc(size))) //不断尝试申请
{
if (g_new_handler_f)
(*g_new_handler_f)(); //期望g_new_handler_f函数里面能够找到可用的内存
else
throw bad_alloc("exception from new.");
}
return p;
}
//delete的一个可能实现
void operator delete( void *ptr )
{
std::cout << "void operator delete( void *ptr )" << std::endl;
if(ptr) // 从这里可以看出,删除一个空指针是安全的
free(ptr);
}
int main()
{
set_new_handler_f(new_handler_f);//设置处理函数
try
{
A* p = new A;
delete p;
}
catch(bad_alloc& e)
{
std::cout << e.what() << std::endl;
}
catch(int)
{
}
system("pause");
return 0;
}
new的一个可能实现
最新推荐文章于 2019-07-15 10:00:22 发布