一个简单的空间置配器.

1612阅读 0评论2011-10-13 lthyxy
分类:C/C++

  1. #include <new>
  2. #include <cstddef>
  3. #include <cstdlib>
  4. #include <climits>
  5. #include <iostream>
  6. #include <vector>
  7. using namespace std;

  8. namespace JJ
  9. {
  10.   template <typename T>
  11.   inline T* _allocate(ptrdiff_t size, T*)
  12.   {
  13.     set_new_handler(0);
  14.     T* tmp = (T*)(::operator new((size_t)(size *sizeof(T))));
  15.     if (tmp == 0)
  16.     {
  17.       cerr << "out of memory!" << endl;
  18.       exit(1);
  19.     }
  20.     return tmp;
  21.   }
  22.   
  23.   template <typename T>
  24.   inline void _deallocate(T* buffer)
  25.   {
  26.     ::operator delete(buffer);
  27.   }
  28.   
  29.   template <typename T1,typename T2>
  30.   inline void _construct(T1* p,const T2& value)
  31.   {
  32.     new(p) T1(value);
  33.   }
  34.   
  35.   template <typename T>
  36.   inline void _destroy(T* ptr)
  37.   {
  38.     ptr->T();
  39.   }
  40.   
  41.   template <typename T>
  42.   class allocator
  43.   {
  44.     public:
  45.       typedef T value_type;
  46.       typedef T* pointer;
  47.       typedef const T* const_pointer;
  48.       typedef T& reference;
  49.       typedef const T& const_reference;
  50.       typedef size_t size_type;
  51.       typedef ptrdiff_t difference_type;
  52.       
  53.       template<typename U>
  54.       struct rebind
  55.       {
  56.         typedef allocator<U> other;
  57.       };
  58.       
  59.       pointer allocate(size_type n, const void *hint=0)
  60.       {
  61.         return _allocate((difference_type)n, (pointer)0);
  62.       }
  63.       
  64.       void dellocate(pointer p, size_type n)
  65.       {
  66.         _dellocate(p);
  67.       }
  68.       
  69.       void construct(pointer p, const T& value)
  70.       {
  71.         _construct(p,value);
  72.       }
  73.       
  74.       void destroy(pointer p)
  75.       {
  76.         _destroy(p);
  77.       }
  78.       
  79.       pointer address(reference x)
  80.       {
  81.         return (pointer)&x;
  82.       }
  83.       
  84.       const_pointer const_address(const_reference x)
  85.       {
  86.         return (const_pointer)&x;
  87.       }
  88.       
  89.       size_type max_size()const
  90.       {
  91.         return size_type(UINT_MAX/sizeof(T));
  92.       }
  93.   };
  94. }

  95. int main()
  96. {
  97.   int ia[5] = {0,1,2,3,4};
  98.   unsigned int i;
  99.   vector<int,JJ::allocator<int>> ivv(ia,ia+5);
  100.   vector<int,std::allocator<int> > iv(ia,ia+5);
  101.   for(i = 0; i < iv.size(); ++i)
  102.    std::cout << iv[i] << " ";
  103.   cout << endl;
  104.   return 0;
  105. }
上一篇:多线程,条件变量
下一篇:构造和析构的基本工具:constuct()和destroy()