calloc 的 boost 池替代方案

发布于 2024-12-10 10:21:57 字数 340 浏览 0 评论 0原文

所有,

如果您使用 boost 池库,您将如何替换以下语句:

MyStruct *someStruct = (MyStruct *) calloc(numOfElements, sizeof(MyStruct));

如果它是针对一个元素,我会这样做:

boost::object_pool<MyStruct> myPool;
MyStruct *someStruct = myPool.malloc();

但由于“numOfElements”是一个变量,我感觉执行 malloc() 循环不是好主意吗?

all,

If you use boost pool library, how would you replace the following statement:

MyStruct *someStruct = (MyStruct *) calloc(numOfElements, sizeof(MyStruct));

If it was for one element, I would do:

boost::object_pool<MyStruct> myPool;
MyStruct *someStruct = myPool.malloc();

but since "numOfElements" is a variable, I have the feeling executing a loop of malloc() is not a good idea?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

北方的巷 2024-12-17 10:21:57

我想说你需要使用 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

I'd say you need to use pool_alloc interface:

static pointer allocate(size_type n);
static pointer allocate(size_type n, pointer);
static void deallocate(pointer ptr, size_type n);

Sample from 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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文