Questions about custom allocators

86 views Asked by At

I would like to create my own allocator class, and I wonder a few things :

  • I have to define the following types : typedef size_t size_type;and typedef ptrdiff_t difference_type;. Can i use something different than size_t ? If I want to use the STL container in a class that uses uint32_t for lengths and positions instead of size_t, can I use uint32_t instead, or does it have to be size_t ? Can it create overflows or other unpleasant things if i use a different type, or even a signed type ?

  • How can I passed a parameter to my allocator ? Do I have to add a constructor with a parameter to it, and construct it manually before passing it to a constructor of the STL container to use it with ?

For the function deallocate 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 the "rebinding" stuff all about ?

..

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

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

Thank you. :)

1

There are 1 answers

0
Axel Borja On BEST ANSWER
  1. This is your allocator, so you can use the type you want. But, note, that if you expect to use it with STL containers, you will have to use a type that STL containers expect. size_t seems appropriate here.

  2. You can provide parameters to your allocator like if it was a normal class. Constructors, initialization methods or setters are fine. In fact, you can provide all functionalities you want to your allocator, but you have to respect the allocate, deallocate signature.

  3. You can ignore the size of your deallocate function. I saw a lot of standard allocator implementations that did not use this parameter. This information could be usefull sometimes, for example if your allocator switch to different allocation strategies depending on size, this parameter could be helpfull in deallocate method to switch on the good deallocate implementation.