Search code examples
c++boostboost-pool

boost pool_allocator memory pool behavior clarification


The boost documentation as below:

Note

The underlying singleton_pool used by the this allocator constructs a pool instance that is never freed. This means that memory allocated by the allocator can be still used after main() has completed, but may mean that some memory checking programs will complain about leaks.

I am confused since I checked the code and the singleton_pool still seem to be created only on the heap of the current process. I.e. if the process is killed by the OS, such pool will be released anyway? Then the above notes merely means if some daemon thread keeps on and such pool is still available after main()? Or it actually means the pool won't be released even after the entire process is killed?

It also seems to me both pool_allocator and fast_pool_allocator are using the identical mechanism to allocate memory i.e. from such a singleton_pool singleton. However this note isn't specified for the fast_pool_allocator. I would reckon both of them behaves the same for such a note above. Am I correct?

Please help. Thanks.


Solution

  • singleton_pool implements thread-safe(under some conditions) singleton without locks, using the feature of initialization of non-local static variables. The part of source code:

    template <typename Tag,
        unsigned RequestedSize,
        typename UserAllocator,
        typename Mutex,
        unsigned NextSize,
        unsigned MaxSize >
    class singleton_pool
    {
       ...
       struct object_creator
       {
          object_creator()
          {  // This constructor does nothing more than ensure that instance()
             //  is called before main() begins, thus creating the static
             //  T object before multithreading race issues can come up.
             singleton_pool<Tag, RequestedSize, UserAllocator, Mutex, NextSize, MaxSize>::get_pool();
          }
          inline void do_nothing() const
          {
          }
       };
       static object_creator create_object;
    }; // struct singleton_pool
    

    non-local variables are initialized as part of program startup, before the execution of the main function begins and get torn down when the program terminates. So that singleton_pool will be created before the main(), and destroyed after main(). If the process is terminated anyway, of course pool will be released.