I am using boost pool as a static memory provider,
void func()
{
std::vector<int, boost::pool_allocator<int> > v;
for (int i = 0; i < 10000; ++i)
v.push_back(13);
}
In above code, how we can fix the size of pool, i mean as we know boost::pool provide as a static memory allocator, but i am not able to fix the size of this pool, its keep growing, there should be way to restrict its size. for example i want a pool of 200 chunks only so i can take 200 chunks after that it should though NULL please let me now how to do this
I don't think boost pool provides what you want. Actually there are 4 other template parameters for
boost::pool_allocator
except the type of object:UserAllocator
: Defines the method that the underlying Pool will use to allocate memory from the system(default =boost::default_user_allocator_new_delete
).Mutex
: Allows the user to determine the type of synchronization to be used on the underlying singleton_pool(default =boost::details::pool::default_mutex
).NextSize
: The value of this parameter is passed to the underlying Pool when it is created and specifies the number of chunks to allocate in the first allocation request (default = 32).MaxSize
: The value of this parameter is passed to the underlying Pool when it is created and specifies the maximum number of chunks to allocate in any single allocation request (default = 0).You may think
MaxSize
is exactly what you want, but unfortunately it's not.boost::pool_allocator
uses a underlyingboost::singleton_pool
which is based on anboost::pool
, theMaxSize
will eventually pass to the data member ofboost::pool<>
:max_size
, so what role does themax_size
play in theboost::pool
? let's have a look atboost::pool::malloc()
:Obviously,
boost::pool
immediately allocates a new memory block if no free chunk available in the memory block. Let's continue to dig into themalloc_need_resize()
:As we can see from the source code,
max_size
is just related to the number of chunks to request from the system next time, we can only slow down the speed of increasing via this parameter.But notice that we can defines the method that the underlying pool will use to allocate memory from the system, if we restrict the size of memory allocated from system, the pool's size wouldn't keep growing. In this way,
boost::pool
seems superfluous, you can pass the custom allocator to STL container directly. Here is a example of custom allocator(based on this link) which allocates memory from stack up to a given size: