boost pool是个不错的库,可以省点内存管理功夫,内存池分配内存,还可以速度上比malloc更快一些。
boost::object_pool主要针对,对象的内存分配,他可以像使用new 一样来创建对象,对象的内存放在object_pool里面。
实际上object_pool使用pool类,代码上是object_pool继承pool类,object_pool比pool多些什么呢,多的就是new 比malloc多的那些内容.
object_pool::construct完成类的内存分配和建构,object_pool::destroy完成类的析构和内存释放。
在使用的过程中遇到一个问题.
class TestPool
{
TestPool(int a0,int a2,int a3,int a4);
};
object_pool<TestPool> p;
p.construct(1,2,34),出错,错误信息叫我看看TestPool的定义,看了几次也没发现什么问题;
把参数改少两个,成功。
调试到一个pool_construct_simple.inc的文件
template <typename T0>
element_type * construct(const T0 & a0)
{
element_type * const ret = malloc();
if (ret == 0)
return ret;
try { new (ret) element_type(a0); }
catch (...) { free(ret); throw; }
return ret;
}
template <typename T0, typename T1>
element_type * construct(const T0 & a0, const T1 & a1)
{
element_type * const ret = malloc();
if (ret == 0)
return ret;
try { new (ret) element_type(a0, a1); }
catch (...) { free(ret); throw; }
return ret;
}
看明白了吧,他是通过定义模板函数来实现建构函数的。
他只实际了3个参数的函数,所以我们需要自已写一个,增加代码如下:
template <typename T0, typename T1, typename T2,typename T3>
element_type * construct(const T0 & a0, const T1 & a1, const T2 & a2,const T3 &a3)
{
element_type * const ret = malloc();
if (ret == 0)
return ret;
try { new (ret) element_type(a0, a1, a2,a3); }
catch (...) { free(ret); throw; }
return ret;
}
element_type * construct(const T0 & a0, const T1 & a1, const T2 & a2,const T3 &a3)
{
element_type * const ret = malloc();
if (ret == 0)
return ret;
try { new (ret) element_type(a0, a1, a2,a3); }
catch (...) { free(ret); throw; }
return ret;
}
好了,一切搞定了,问题消失了。
生活怎么就这么没劲呢???
lixiaomail
2008-08-14

