参考:http://oss.org.cn/?action-viewnews-itemid-3744
allocator 是一个类,有着叫allocate()和deallocate()成员函数(相当于malloc和free)。它还有用于维护所分配的内存的辅助函数和指示如何使用这些内存的typedef(指针或引用类型的名字)。
举个例子vector::get_allocator(代码来自http://www.cplusplus.com/reference/stl/vector/get_allocator/)
// vector::get_allocator #include <iostream> #include <vector> using namespace std; int main () { vector<int> myvector; int * p; unsigned int i; // allocate an array of 5 elements using vector's allocator: p=myvector.get_allocator().allocate(5); // assign some values to array for (i=0; i<5; i++) p[i]=i; cout << "The allocated array contains:"; for (i=0; i<5; i++) cout << " " << p[i]; cout << endl; myvector.get_allocator().deallocate(p,5); return 0; }Returns the allocator object used to construct the vector.
allocator也参考(You can see an example of a pool allocator in the open source SGIPro64TM?compiler):http://oss.sgi.com/projects/Pro64/
也参考:http://www.cplusplus.com/reference/std/memory/allocator/
类模板allocator的定义如下:
template < class T > class allocator;
Taking one template parameter (which is assumed to be T in this entire reference).
其成员变量和成员函数如下:
member | definition in allocator | represents |
---|---|---|
value_type | T | Element type |
pointer | T* | Pointer to element |
reference | T& | Reference to element |
const_pointer | const T* | Constant pointer to element |
const_reference | const T& | Constant reference to element |
size_type | size_t | Quantities of elements |
difference_type | ptrdiff_t | Difference between two pointers |
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; };