使用boost pool的简单例子如下:
#include <cstdlib>
#include <iostream>
#include <boost/pool/pool.hpp>
#include <boost/pool/object_pool.hpp>
using namespace std;
using namespace boost;
class Object
{
public:
Object(){cout<<"new obj"<<endl;}
~Object(){cout<<"delete obj"<<endl;}
};
int main(int argc, char *argv[])
{
//!每次分配的块的大小
const int blocksize = sizeof(int);
boost::pool<> alloc(blocksize);
for(int i = 0; i < 100; i++)
{
//! 分配
int* ptr = (int*)alloc.malloc();
cout<<*ptr<<endl;
//! 释放
alloc.free(ptr);
}
//!object pool每次需要指定对象大小
boost::object_pool<Object> pool_alloc;
for(int i = 0;i < 100;i++)
{
//! 分配内存
void* mem = pool_alloc.malloc();
//! 构造
Object *obj = new(mem)Object();
//! 析构
pool_alloc.destroy(obj);
}
system("PAUSE");
return EXIT_SUCCESS;
}
//! ccsdu2004