SGI的标准的空间适配器 allocator

来源:互联网 发布:python setdefault函数 编辑:程序博客网 时间:2024/05/11 20:46
// SGI STL 配置器的实现#include <new>#include <cstddef>#include <cstdlib>#include <limits>#include <iostream>//#include <algobase>size_t max(size_t a, size_t b)//由于没找到algobase 头文件我自己完成了这个max {    if(a>b)        return a;    else        return b;}template <typename T>inline T * allocate (ptrdiff_t size , T *){    T * tmp = (T*) (::operator new ((size_t)(size * sizeof(T))));//申请size * T大小的空间并强制转化为size_t(unsigned int)类型 再把头地址的T*指针赋予tmp    if(tmp == 0)    {        std::cout << "out of memory" <<std::endl;        exit(1);     }      return tmp;}template <typename T>inline void deallocate(T * p){    ::operator delete(p);}template <typename 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;    pointer allocate(size_type n)    {        return allocate( (difference_type)n, (pointer)0);//没有看出吧size_t类型转化为ptrdiff_t类型的必要,第二个参数我自己会写成NULL;     }    void deallocate(pointer p)    {        dellocate(p);    }    pointer address (reference x)    {        return (pointer)&x;//返回存有X地址的指针     }    const_pointer const_address(const_reference x)    {        return (const_pointer)&x;    }    size_type init_page_size()    {        return  max(size_type(1),size_type(4096/sizeof(T))) ;//返回每个元素所占的大小?     }    size_type max_size() const//这里的const表示函数无法修改类的成员     {        return max(size_type(1),size_type(UINT_MAX/sizeof(T)));    }}; class allocator<void> //给出一个空特例? 在DEV C++ 编译环境下会出现没有丁页template的错误.  {    public:        typedef void *pointer;  } ;

这个allocator的实现其实和上次的空间适配器简易实现的思路相同,我只是练手顺便写了下来。

0 0
原创粉丝点击