template<class T>
class allocator {
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef T *pointer;
typedef const T *const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef T value_type;
pointer address(reference x) const;
const_pointer address(const_reference x) const;
allocator();
allocator<T>& operator=(const allocator<T>);
pointer allocate(size_type n, const void *hint);
void deallocate(pointer p, size_type n);
void construct(pointer p, const T& val);
void destroy(pointer p);
size_type max_size() const;
};
The template class describes an object that manages storage allocation and freeing for arrays of objects of type T
. An
object of class allocator
is the default allocator object specified in the constructors for several container template
classes in the Standard C++ library.
Template class allocator
supplies several type definitions that are rather pedestrian. They hardly seem worth
defining. But another class with the same members might choose more interesting alternatives. Constructing a container
with an allocator object of such a class gives individual control over allocation and freeing of elements controlled by that
container.
For example, an allocator object might allocate storage on a private heap. Or it might allocate storage on a far heap, requiring nonstandard pointers to access the allocated objects. Or it might specify, through the type definitions it supplies, that elements be accessed through special accessor objects that manage shared memory, or perform automatic garbage collection. Hence, a class that allocates storage using an allocator object should always use these types for declaring pointer and reference objects (as do the containers in the Standard C++ library).
Thus, an allocator defines the types (among others):
pointer
-- behaves like a pointer to T
const_pointer
-- behaves like a const pointer to T
reference
-- behaves like a reference to T
const_reference
-- behaves like a const reference to T
These types specify the form that pointers and references must take for allocated elements.
(allocator::types<T>::pointer
is not necessarily the same as T *
for all allocator objects, even though it has
this obvious definition for class allocator
.)
In this implementation, if a translator does not support member template functions, it omits the type-mapping member template class:
template<class U>
struct rebind {
typedef allocator<U> other;
};
Thus, how you write an allocator is constrained. A container may need to allocate and free objects other than type T
,
but cannot use the rebind
mechanism to derive a suitable allocator object. This means you cannot write an allocator that
uses any pointer or reference types that differ from those used by allocator
, and you must supply the member
function:
char *_Charalloc(size_type n);
which allocates an object of size n
bytes and returns a pointer to its first byte.