I am trying to write a container class which uses STL allocators. What I currently do is to have a private member
std::allocator<T> alloc_;
(this will later be templated so that the user can pick a different allocator) and then call
T* ptr = alloc_.allocate(1,0);
to get a pointer to a newly allocated ‘T’ object (and used alloc_.construct to call the constructor; see the answer below). This works with the GNU C++ library.
However, with STLPort on Solaris, this fails to do the right thing and leads to all sorts of bizarre memory corruption errors. If I instead do
std::allocator_interface<std::allocator<T> > alloc_;
then it is all working as it should.
What is the correct way to use the stl::allocator? The STLPort/Solaris version fails to compile with g++, but is g++ right?
Something you might want to do is have your own custom
allocatorthat you can use to see how the standard containers interact wit allocators. Stephan T. Lavavej posted a nice, simple one called themallocator. Drop it into a test program that uses various STL containers and you can easily see how the allocator is used by the standard containers:Not all of the interface functions in the
mallocator(such asconstruct()anddestroy()) are instrumented with trace output, so you might want to drop trace statements in there to more easily see how the standard containers might use those functions without resorting to a debugger.That should give you a good idea of how your containers might be expected to use a custom
allocator.