通过重载new和delete实现简单的对象池
对象池的用途在这里就不介绍了,本例中只是其一个简单的实现。
#include
<list>
#include
<iostream>
using
namespace std;
template<class T>
class object_pool
{
list<void *> data_list;
public:
void* malloc_data()
{
if(!data_list.empty())
{
list<void *>::iterator it = data_list.begin();
void *p = *it;
data_list.pop_front();
return p;
}
else
{
void* p = malloc(sizeof(T));
return p;
}
}
void free_data(void* p)
{
data_list.push_back(p);
}
};
class A
{
public:
int value;
A(int a):value(a){cout<<"A("<<a<<") called"<<endl;}
~A() {cout<<"~A("<<value<<") called"<<endl;}
static object_pool<A> pool_;
void* operator
new (size_t size)
{
return pool_.malloc_data();
}
void
operator
delete(void* p)
{
pool_.free_data(p);
}
};
object_pool<A> A::pool_;
void main()
{
A* a1=new A(1);
delete a1;
A* a2=new A(2);
delete a2;
}
^_^