Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I'm using a third-party library which utilizes boost::shared_ptr for memory management.

The problem is that I need to allocate many objects and I have detected that the allocation and deallocation is rather resource-demanding. So I thought I should utilize a smart-pointer memory pool to reduce the overhead.

#include <boost/smart_ptr/make_shared_array.hpp>

template <class T, size_t pool_size>
class shared_ptr_pool
{
   boost::shared_ptr<T[]> pool;
   size_t avail = 0;

public:
   boost::shared_ptr<T> make_shared()
   {
      if (!avail)
      {
         pool = boost::make_shared<T[]>(pool_size);
         avail = pool_size;
      }

      return boost::shared_ptr<T>(pool, &pool[--avail]);
   }
};

The solution is to utilize make_shared for arrays and the shared_ptr aliasing constructor. The solution in inherently thread-unsafe, but for my needs that is okay.

Any thoughts, comments or pretty much anything would be appreciated.

share|improve this question
    
The main advantage of a pool is that released pointers can quickly be re-used. I don't see that functionality here. Once your pool is empty you need to re-create another pool. –  Loki Astari Mar 24 at 1:07
    
This might be a silly question. But why would you use a third party library for something that is already in the language? –  Mads Mar 25 at 1:26
    
@Mads: The third-party library I use in turn use boost::shared_ptr because of performance, portability and it correctly uses delete[] on array types. –  dalle Mar 25 at 8:44
    
@LokiAstari: You are correct, this isn't a pool as such, as it doesn't return objects to the pool, but a chunk-allocator-thingy (?). –  dalle Mar 25 at 8:46

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.