Questions about custom allocators

I would like to create my own allocator class and I am interested in a few things:

  • I need to define the following types: typedef size_t size_type;

    and typedef ptrdiff_t difference_type;

    . Can I use something other than size_t

    ? If I want to use an STL container in a class that uses uint32_t

    for lengths and positions instead size_t

    , can I use uint32_t

    or should it be size_t

    ? Could it create overflows or other nasty things if I use a different type, or even a signed type?

  • How do I pass a parameter to my allocator? Do I have to add a parameterized constructor to it and create it manually before passing it to the STL container constructor to use with?

For the deallocate function of the function defined below, can I just ignore the number of items to deallocate?

void deallocate( pointer p, size_type nNum )
{
   (void) nNum;
   delete[] p;
}

      

  • What is "rewrite" material?

..

template< class U >
struct rebind
{
    typedef Allocator< U > other;
};

template< class U >
Allocator( const Allocator< U > & oAlloc )

      

Thank.:)

+3


source to share


1 answer


  • This is your distributor, so you can use the type you want. But, note that if you plan to use it with STL containers, you will have to use the type that STL containers expect. size_t

    seems appropriate here.

  • You can provide parameters to your allocator as if it were a normal class. Constructors, initialization methods, or setters are fine. In fact, you can provide all the functionality you want for the allocator, but you have to respect the allocation, release the signature.

  • You can ignore the size of the deallocate function. I've seen a lot of standard allocator implementations that don't use this option. Sometimes this information can be helpful, for example if your allocator switches to different allocation strategies based on size, this parameter can be useful in the deallocate method to enable a good deallocate implementation.



+2


source







All Articles