STL::allocator rebind

          阅读侯捷的STL源码剖析时,发现在allocator类的代码中有这样一个struct

template<class T>
class allocator
{
    ...
    template<class U>
    struct rebind
    {
        typedef allocator<U> other;
    };
    ...
};

          起初觉得很申必,因为无论是注释还是后续的代码中都没有提到此rebind。后来百度了一下知道了其实际意义,记录一下。

         

          rebind的意义就在于实现两个不同但两者互相有关的类型(比如类型T和Node<T>类型),使用同一种内存分配方法。

          如果抛开rebind不提,想要实现上述的意义,容器必须要让allocator是同一个模板,问题就出在容器并不关心你的allocator是怎么写的,他唯一有关的就是在声明时在template中写alloc = allocator<T>,只知道模板参数名allocator,而不知道其具体实现,导致没有办法让T与U的allocator是同一个。

          于是在allocator<T>中创建一个U的allocator,标准中有这样的规定:

          对于allocator<T>与一个类型U,allocator<U>与allocator<T>::rebind<U>::other是等价的。

         

          在想使用allocator<U>的时候就需要使用allocator<T>::rebind<U>::other,否则就是用了一个别的allocator了。

         

          //todo:之后可能会补个rebind的范例,或者是单独的写个blog,先放着吧

原文地址:https://www.cnblogs.com/HotPants/p/11443291.html