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;
andtypedef ptrdiff_t difference_type;
. Can I use something other thansize_t
? If I want to use an STL container in a class that usesuint32_t
for lengths and positions insteadsize_t
, can I useuint32_t
or should it besize_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.:)
source to share
-
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.
source to share