User-Defined Allocator

The C++ Standard Template Library STL as part of the C++ Standard Library allows to use allocators as abstractions of the memory model. Allocators are used to translate the need to use memory into a raw call for memory. This page gives an example of a standard conforming user-defined allocator and its usage.

The example defines an allocator, called MyAlloc<> in myalloc.hpp. This allocator uses the global operators new and delete to allocate and deallocate memory. As a special feature, it prints messages on the standard error channel cerr whenever memory is allocated or deallocated.

myalloc.hpp:

  • as HTML file
  • as plain file

  • Example for using MyAlloc<>:

  • as HTML file
  • as plain file
  • This code, at least, compiles with gcc-2.95.2 and libstdc++, version 2.90.7.

    To find more details about allocators in general and user-defined allocators, see
         The C++ Standard Library - A Tutorial and Reference
         by Nicolai M. Josuttis

         Addison Wesley Longman, 1999

         ISBN 0-201-37926-0

    Home Page