shared_ptr with a memory pool

  • Jason Leger
    Jason Leger


    The program I am writing will create and delete a lot of objects. 
    These objects will be referenced from multiple places.

    Obviously, I need a shared_ptr, however, I am worried about the performance during creation and deletion

    Can you use a boost::pool interface with the shared_ptr?

    I have tried using the pool, object_pool, singleton_pool interfaces but I can't get the constructor to run on my object.

    If I use the pool_alloc interface I have to use a container.

    Basically, I want to allocate objects from a memory pool and have these object pointed to by smart/shared_ptr so that when all of the references to the object are gone the object is deleted.

    Can anyone help me? 

    • Klaus Ahrens
      Klaus Ahrens


      i read in the docs:

      "Because the implementation uses reference counting, cycles of shared_ptr instances will not be reclaimed. For example, if main() holds a shared_ptr to A, which directly or indirectly holds a shared_ptr back to A, A's use count will be 2. Destruction of the original shared_ptr will leave A dangling with a use count of 1. "
      trying to provoke such a cycle with

      #include <iostream>
      #include <boost/smart_ptr.hpp>

      class X {
          boost::shared_ptr<X> link;
          X():link(this){std::cout<<"X created at "<<this<<"\n";}
          ~X(){std::cout<<"X destroyed at "<<this<<"\n";}

      int main()
          boost::shared_ptr<X> px(new X);

          std::cerr<<"use count is "<<px.use_count()<<std::endl;   

      i get (with g++ (GCC) 3.3.3 (SuSE Linux)) a double

      X created at 0x804b008
      use count is 1
      X destroyed at 0x804b008
      X destroyed at 0x804b008

      very puzzled ....