Rogue Wave banner
Previous fileTop of DocumentContentsIndex pageNext file
Essential Tools Module User's Guide
Rogue Wave web site:  Home Page  |  Main Documentation Page

11.6 Using Custom Allocators

The STL and STL extension-based classes now accept an additional template allocator argument. The allocator argument has a default value of std::allocator<T> derived from the Standard C++ Library.

The use of custom allocators depends on the ANSI compliance of your compiler and your Standard C++ Library implementation. If allocators can be used, you can also provide your own allocator to customize memory management in an application.

In order to provide your own class template as an allocator, the template must conform to the particular interface described by the Standard C++ Library. This consists of member functions and typedefs as well as their syntactic and semantic requirements.

Here is a partial code snippet of a simple allocator:

The rebind member allows a container to construct an allocator for some arbitrary data type. The allocator type is determined by the template parameter.

For example, a container may need to allocate types other than T (i.e. list nodes or hash buckets). In this case the container could obtain correct type, typically with a typedef:

User-defined allocators must also be equality comparable; if a and b are instances of a user-defined allocator, then the expressions (a == b) and (a != b) must be well-formed.

11.6.1 Template Functions

Allocator class templates must meet all the above requirements. They must also provide these other member functions.

Constructors

Destructor

Assignment operators

Public Member Functions

pointer address(reference r) const;
const_pointer address(const_reference r) const;
pointer allocate(size_type n,
allocator<U>::const_pointer hint=0);
void deallocate(pointer);
size_type max_size();
void construct(pointer p, const_reference val);
void destroy(pointer p);

11.6.2 Example

The example below defines a simple custom allocator. This can be used to test your compiler or the Standard C++ Library's support for custom allocators. It checks if the allocator argument that is passed in the code is actually used:

Program Output

In the output listed above, it can be seen that, when no custom allocator was used, the RWTValDist was created and 100 items were inserted. However, when the list was instantiated with my_allocator, instances of this class were used in 8 allocations and deallocations of heap memory. This proves that the example used my_allocator for memory management.



Previous fileTop of DocumentContentsIndex pageNext file

Copyright © Rogue Wave Software, Inc. All Rights Reserved.

The Rogue Wave name and logo, and SourcePro, are registered trademarks of Rogue Wave Software. All other trademarks are the property of their respective owners.
Contact Rogue Wave about documentation or support issues.