18. Appendix D: Allocator Class

Several STL components use Default Template Arguments. The ANSII draft specification for the STL container classes (such as vector) dictates that the template parameter that specifies the allocator must have a default value of "allocator", as follows:

template<class T, class Allocator = allocator> class vector;

The class allocator as specified by the ANSII draft standard utilizes member templates. Visual C++ version 4.2 does not support the use of member templates. (The term member template refers to one or more methods of a (possibly nontemplated) class that are defined as templated functions. It can also be used to describe a class that has an embedded template class.)

Since it is not possible to implement the class allocator directly, allocator has been implemented as a template class in the current implementation of the STL. The problem lies in attempting to use the templated allocator class as a default template argument. Consider the following:

template<class T, class Allocator = allocator<T> > class vector;

This new construct with the template allocator class creates a circular reference, because it relies on the unknown data type T to instantiate the allocator class. This makes it necessary, in the case of STL containers, to remove the default template argument for the allocator. The definition of vector now becomes:

template<class T, class Allocator> class vector;

Therefore, declaring a container will now require that you explicitly specify the allocator class as a template argument, as the following declaration of an int vector illustrates:

vector<int> myVector;

This declaration will cause the following compiler error:

Compiler error C2976 : 'vector' : too few template parameters

To correct the error, the declaration must be changed to:

vector<int, allocator<int> > myVector; 

Note   The STL is an emerging technology. The definition of the allocator class as a templated class will undoubtedly change in a future release of Visual C++. You should always use typedefs when using any component of the STL—this will make it relatively painless to update your code if and when the templates change.