本文参考http://blog.csdn.net/xushiweizh/archive/2006/11/21/1400426.aspx
并查阅了boost 的一些官方文档。
boost::pool 适用微小对象,这些对象被分配至堆上。它们应该没构造函数,析构函数。
可以看成一个种小型自定义数据类型。
boost::object_pool 适用于细粒度的对象,可以拥有无参数的构造函数和析构函数。
用代码说话。
以下代码都经本人编译运行过
//testpool.cpp
for(int i=0; i<SIZE; ++i)
{
cout << *ptrs[i] << endl;
}
//pool的析构函数会释放所有从系统申请到的内存
//因pool被分配栈上,所以当退栈后,自动调用其析构函数
//即分配在pool上的众多小对象不用手动释放内存
}
//见boost pool官方文档
// on function exit, pool is destroyed, and all malloc()'ed ints are implicitly freed
//TestObject_pool.cpp
cout << "test object pool" << endl;
vector<Pt2D *>::iterator itSt, itEnd;
for(itSt = vec.begin(), itEnd = vec.end();
itSt != itEnd; ++itSt)
{
cout <<"X= " << (*itSt)->x<< " Y= "<<(*itSt)->y << endl;
}
boost::object_pool<Line> linesPool;
for(int i=0; i<SIZE; ++i)
{
//Line * line = linesPool.malloc();
Line * line = linesPool.construct(); // 在分配的内存上调用无参构造函数
}
}
// on function exit, p is destroyed, and all malloc()'ed ints are implicitly freed
//当函数退出时,pool会调用每个对象的析构函数,见以下boost源码
/*
template <typename T, typename UserAllocator>
object_pool<T, UserAllocator>::~object_pool()
{
//......
// This chunk is not free (allocated), so call its destructor
static_cast<T *>(static_cast<void *>(i))->~T();
// and continue searching chunks in the memory block
//......
}
*/
相关资料及代码
http://download.csdn.net/source/2560388