空间适配器:空间适配器是STL实现的一个基础。整个STL操作的对象(所有的数值)都存放在容器之内,而容器一定需要配置空间以置放资料。(这里的空间配置器的空间可以是磁盘或其它辅助的存储介质,在SGI STL中是内存)
空间适配器的标准接口:
以下提供一份std标准的allocator,在SGI中是defalloc.h,但是SGI没有使用它,原因是效率过低,但是作为讲解标准接口是一个比较好的例子
代码:
#ifndef DEFALLOC_H #define DEFALLOC_H #include <new.h> #include <stddef.h> #include <stdlib.h> #include <limits.h> #include <iostream.h> #include <algobase.h> template <class T> inline T* allocate(ptrdiff_t size, T*) { set_new_handler(0); T* tmp = (T*)(::operator new((size_t)(size * sizeof(T)))); if (tmp == 0) { cerr << "out of memory" << endl; exit(1); } return tmp; } template <class T> inline void deallocate(T* buffer) { ::operator delete(buffer); } template <class T> class allocator { public: typedef T value_type; typedef T* pointer; typedef const T* const_pointer; typedef T& reference; typedef const T& const_reference; typedef size_t size_type; typedef ptrdiff_t difference_type; pointer allocate(size_type n) { return ::allocate((difference_type)n, (pointer)0); } void deallocate(pointer p) { ::deallocate(p); } pointer address(reference x) { return (pointer)&x; } const_pointer const_address(const_reference x) { return (const_pointer)&x; } size_type init_page_size() { return max(size_type(1), size_type(4096/sizeof(T))); } size_type max_size() const { return max(size_type(1), size_type(UINT_MAX/sizeof(T))); } }; class allocator<void> { public: typedef void* pointer; }; #endif
首先是各种type:其实就是typedef
allocator:: value_type:
allocator:: pointer:
allocator:: const pointer:
allocator:: reference:
allocator:: size_type
allocator:: difference_type:
结合上面的文件,某些类型很容易就知道它要表达的意思,这里只讲一下typedef ptrdiff_t difference_type
ptrdiff_t 这是一个和机器相关的数据类型,它是用来保存两个指针减法操作的结果,通常定义为long int,它必须保证能存放同一数组中两个指针之间的差距(也就是说这个类型要保存两个指针之间距离的大小,比如我对两个同类型的数据取址,ptrdiff_t可以保存两者之间的差值,这个值可正可负,与size_t不一样,size_t用于指明数组长度,必须为正)
然后是allocator的必要接口:
allocator::rebind:一个嵌套的(nested)class template。class rebind<U>拥有唯一成员other(上文提供的文件中无)
allocator::allocator():默认构造函数
allocator::allocator():复制构造函数
allocator::allocator():泛化的复制构造函数
allocator::~allocator():默认的析构函数