所有
如果您使用boost池库,您将如何替换以下语句:
MyStruct *someStruct = (MyStruct *) calloc(numOfElements, sizeof(MyStruct));
如果是一个元素,我会这样做:
boost::object_pool<MyStruct> myPool;
MyStruct *someStruct = myPool.malloc();
但由于“numOfElements”是一个变量,我觉得执行malloc()循环不是一个好主意吗?
答案 0 :(得分:3)
我说你需要使用pool_alloc
界面:
static pointer allocate(size_type n);
static pointer allocate(size_type n, pointer);
static void deallocate(pointer ptr, size_type n);
来自http://www.boost.org/doc/libs/1_47_0/libs/pool/doc/interfaces.html
的示例void func()
{
std::vector<int, boost::pool_allocator<int> > v;
for (int i = 0; i < 10000; ++i)
v.push_back(13);
} // Exiting the function does NOT free the system memory allocated by the pool allocator
// You must call
// boost::singleton_pool<boost::pool_allocator_tag, sizeof(int)>::release_memory()
// in order to force that