手撸STL——————>allocator
一。什么是allocator
所有标准库的容器,在存储、销毁元素时都会涉及分配内存。由于元素类型不同,不可能写出所有类型的分配方法,所以利用c++模板机制,构造出一个通用的分配工具—->allocator。
二。allocator的定义
cppreference上的allocator定义:
The std::allocator class template is the default Allocator used by all standard library containers if no user-specified allocator is provided. The default allocator is stateless, that is, all instances of the given allocator are interchangeable, compare equal and can deallocate memory allocated by any other instance of the same allocator type.
allocator作为一个类模板,当用户(coder)没有特别给出自己的配置器时,是所有标准库容器的默认空间配置器。默认allocator是没有任何状态的(stateless,没有成员变量,只有成员函数和类型定义),也就是说,给定allocator的所有实例都是
- 不可更改的
- 无差别的
- 能够销毁任何其他allocator(相同模板类型)所分配的内存
三。allocator的elements需求
member types:
public:
typedef T value_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& referrence;
typedef const T& const_reference;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
template
struct rebind {
typedef allocator other;
};//一个allocator只能分配一种内存,未免不够,有时还需要分配其他内存,所以加上一个rebind,充当萃取剂,提炼出另一种类型
member functions:
未完待续