Re: Custom Allocator Question - Advanced.
On May 23, 9:46 pm, joe <joeyc...@mail.com> wrote:
I have written a custom std allocator which follows the example in
Stroustrup's book.
I'm seeing a behavior I don't understand.
My allocate method within the allocator looks like the following:
(FooAllocator<T>)
pointer allocate(size_type cnt, typename
std::allocator<void>::const_pointer hint = 0)
{
pointer p = reinterpret_cast<pointer> (new char[sizeof(T)*cnt]);
std::cout<<"MEMORY ADDRESS: "<<p<<std::endl; //FIRST PRINT-OUT!
return p;
}
Then I have a regular container in my main:
int main()
{
typedef std::multiset<Foo,less<Foo>,FooAllocator<Foo> > MYSET;
MYSET mine;
MYSET::iterator iter = mine.insert(Foo());
std::cout<<"ITER = "<<&(*iter)<<std::endl;
}
The address of the iterator being returned is 16 Bytes graeter than
the address of the allocated memory. This is true in multiple
compilers, and is causing me to overwrite the end of my allocated
memory. It doesn't seem to matter what type of object Foo is.
Presumably (I don't see how one could implement it differently),
what is being allocated in the multiset is not a T, but some
sort of node structure containing a T, typically with a couple
of pointers before the T. And the actual type of the allocator
being used to do the allocation should not be T, but this node
type.
Having said this, I don't quite see how this could be causing
you to overwrite anything. The allocation expression should be
something like (typedef's expanded, etc.):
__Alloc::rebind<__Node>::other( myAlloc ).allocate( n )
If you're rebind declaration is correct, and the code for
allocate is really what you show, then you should have no
trouble in this respect; if you're not sure, add output of
typeid(T).name and sizeof(T) to your allocator, to see what is
going on.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34