allocator类是C++的一个模板,它提供类型化的内存分配以及对象的分配和撤销。allocator类将对象分配和对象构造分开。当allocator对象分配内存的时候,它会分配适当大小并排列成保存给定类型对象的空间。下面是allocator 的一个简单实现:
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 T1,class T2>
inline void _construct(T1 *p, T2& value) {
new(p) T1(value);
}
template<class T>
inline void _destroy(T *ptr) {
ptr->~T();
}
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;
template<class U>
struct rebind {
typedef allocator<U>other;
};
pointer allocate(size_type n, const void* hint = 0) {
return _allocate((difference_type)n,(pointer)0);
}
void deallocate(pointer p, size_type n) { _deallocate(p); }
void construct(pointer p, const T& value) {_construct(p,value);}
pointer address(reference x) { return (pointer)&x; }
const_pointer const_address(const_reference x) {
return (const_pointer)&x;
}
size_type max_size()const {
return size_type(UINT_MAX/sizeof(T));
}
};
allocator类是C++的一个模板,它提供类型化的内存分配以及对象的分配和撤销。allocator类将对象分配和对象构造分开。当allocator对象分配内存的时候,它会分配适当大小并排列成保存给定类型对象的空间。
下面是allocator类的使用:
allocator<string>alloc; //可以分配string的allocator对象
auto const p=alloc.allocate(n); //分配n个未初始化的string
allocator 分配的内存是未构造的。我们按需要在此内存中构造对象。在新标准库中,construct 成员函数接受一个指针和零个或多个额外参数,在给定位置构造一个元素。额外参数用来初始化构造对象。
auto q=p; //q指向最后构造的元素之后的位置
alloc.construct(q++); //*q为空字符串
alloc.construct(q++,10,'c'); //*q为cccccccccc
alloc.construct(q++,"hi"); //*q为hi
当用完对象后,必须对每个构造的元素调用destroy 来销毁它们。函数destroy 接受一个指针,对指向的对象执行折钩函数:
while(q!=p)
alloc.destroy(--q); //释放我们真正构造的string
一旦元素被销毁后,就可以重新使用这部分内存来保存其他 string,也可以将其归还给系统。释放内存通过调用 deallocate 来完成:
alloc.deallocate(p,n);
传递给deallocate的指针不能为空,它必须指向由allocate 分配的内存。而且,传递给 deallocate 的大小参数必须与调用 allocated分配内存时提供的大小参数具有一样的值。