I'm using boost::intrusive_ptr
to handle automatic memory management, but now I'd like to use them in conjunction with pooled object allocation. Would Boost Pool be a good starting point for this, or is there another generally accepted practice for pooled allocation with "smart pointers?"
Asked
Active
Viewed 454 times
2

Some programmer dude
- 400,186
- 35
- 402
- 621

fredbaba
- 1,466
- 1
- 15
- 26
-
I have written an answer to another question about boost::pool: http://stackoverflow.com/a/17671067/1918154 . So my suggestion is to not use it. – Jan Herrmann Aug 06 '13 at 06:24
-
These are independent matters. If you override `new/delete` `boost::intrusive_ptr` with defaults works seemlessly. – Maxim Egorushkin Aug 06 '13 at 09:26
-
@JanHerrmann, thanks for the link. I think I'm going to use a custom allocator based on my particular use case. @MaximYegorushkin, I worry that overriding `new/delete` might be a bit inflexible. I like that `boost::intrusive_ptr` is an "opt-in" policy, i.e. you can choose whether or not to use the memory management at runtime. I can see cases where I'd want both pooled and `new`'d instances to exist in the same application... – fredbaba Aug 07 '13 at 01:33
1 Answers
0
I think I wrote exactly what you are looking for:
https://github.com/cdesjardins/QueuePtr
It is basically a thread safe queue, that gets populated at init time with memory buffers:
boost::shared_ptr<RefCntBufferPool> pool(new RefCntBufferPool(700, 1024));
There you have a shared_ptr to a pool that has 700 buffers in it, and each buffer is 1024 bytes.
Then you can get a buffer:
boost::intrusive_ptr<RefCntBuffer> x;
pool->dequeue(x);
and do what you like with it, here are some examples:
boost::intrusive_ptr<RefCntBuffer> y;
y = x;
y->_buffer = boost::asio::buffer(y->_buffer + 10, 100);
boost::asio::buffer_copy(y->_buffer, boost::asio::buffer("hello"));
x.reset();
When the reference count drops to indicate that the buffer is no longer in use it gets put back in the pool automatically and can be reused, the buffer is also reset to it's original memory allocation in case you messed it up (as I did above) during use.

Chris Desjardins
- 2,631
- 1
- 23
- 25