1

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?

pinpinokio
  • 505
  • 5
  • 19

1 Answers1

3

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
sehe
  • 374,641
  • 47
  • 450
  • 633
  • Would a call to `vector::reserve` still make sense when a `pool_allocator` is used? – pmr Oct 18 '11 at 12:35
  • @pmr: I guess; what do you reckon vector::reserve would _do_?(http://www.sgi.com/tech/stl/Allocators.html) – sehe Oct 18 '11 at 12:40
  • I was just thinking that calling `reserve` might would interfere with the allocation strategy of the underlying pool. My experience with `pool_alloc` is bad and I suspect that I developed trust issues. ;) – pmr Oct 18 '11 at 12:47
  • @pmr: you might be right. this is always true when substituting custom allocators. I haven't much experience with boost pool – sehe Oct 18 '11 at 12:51
  • "Exiting the function does NOT free the system memory allocated" - but also does not allocate it ... as far as I see, you still need to make a loop in order to allocate 10000 elements ... – pinpinokio Oct 18 '11 at 12:54
  • The example does. However, `std::vector > v(10000);` changes it. I like to quote canonical examples, so I can't mess things up :) The comment is also verbatim, and I'm not sure how it relates (because I don't know how boost::singleton_pool is involved). YMMV, but you can _certainly_ do better than a loop – sehe Oct 18 '11 at 12:56