今天实现了一个粗陋的stl allocator ,算是一天时间,没有白费,希望今后对STL原理更加理解深入吧,同时,对c++的细节更多的进行试验和掌握。
自定义allocator中比较关键,难于理解的是rebind这个结构体模板,其实静下心来就好理解了,这是针对节点型容器的适配吧算是,
有三个作用:
1. 让容器内部知道allocator的具体实现的名字;
2. -Ty和_Other是有联系的;
3. 从而能够在容器内部形成和_Ty同族的分配器;
class allocator<class _Ty>
{
template<class _Other>
struct rebind
{
typedef alloctor<_Other> other;
};
};
比如list容器,list<int, allocator<int> >, 内部并不是将allocator<int>作为分配器的,这只是一个假象,真正的allocator特化类型是allocator<listnode>,
只不过通过通过allocator接口比较难于兼容,所以定义rebind模板
相当于真正的allocator是:
typedef allocator<_Ty> Alloc;
Alloc::rebind<ListNode>::other