提升Calloc的替代池替代品
-
25-10-2019 - |
题
全部,
如果您使用Boost池库,则如何替换以下语句:
MyStruct *someStruct = (MyStruct *) calloc(numOfElements, sizeof(MyStruct));
如果是一个元素,我会做:
boost::object_pool<MyStruct> myPool;
MyStruct *someStruct = myPool.malloc();
但是,由于“数字”是一个变量,所以我感觉执行malloc()的循环不是一个好主意吗?
解决方案
我会说你需要使用 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
不隶属于 StackOverflow