CUJ:标准库:Allocator能做什么?[5]

[入库:2005年8月18日] [更新:2007年3月24日]

本文简介:选择自 taodm 的 blog

    (为什么allocator有那些成员函数,什么时候容器可以直接使用placement new?一个理由是要隐藏笨拙的语法,而另一个是如果写一个更复杂的allocator时你可能想在构造和销毁对象时construct()和destroy()还有其它一些副作用。比如,allocator可能维护一个所有当前活动对象的日志。)

    这些成员函数没有一个是static的,因此,容器在使用allocator前做的第一件事就是创建一个allocator对象--也就是说我们应该定义一些构造函数。但是,我们不需要赋值运算:一旦容器创建了它的allocator,这个allocator就从没想过会被改变。表32中的对allocator的需求没有包括赋值。只是基于安全,为了确保没人偶然使用了赋值运算,我们将禁止掉这个可能自动生成的函数。

    template <class t> class malloc_allocator

    {

    public:

      malloc_allocator() {}

      malloc_allocator(const malloc_allocator&) {}

      ~malloc_allocator() {}

    private:

      void operator=(const malloc_allocator&);

      ...

    };

    这些构造函数实际上没有做任何事,因为这个allocator不需要初始化任何成员变量。基于同样的理由,任意两个malloc_allocator都是可互换的;如果a1和a2的类型都是malloc_allocator<int>,我们可以自由地通过a1来allocate()内存然后通过a2来deallocate()它。我们因此定义一个比较操作以表明所有的malloc_allocator对象是等价的:

    template <class t>

    inline bool operator==(const malloc_allocator<t>&,

                           const malloc_allocator<t>&) {

      return true;

    }

    template <class t>

    inline bool operator!=(const malloc_allocator<t>&,

本文关键:CUJ、allocator、STL、Matt Austern
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top