基于前面内存分配器的STL内存分配器

    使用起来很简单,像这样:

typedef std::list< int, std::SR_allocator<int> >   IntList;

typedef std::set< INT, std::less<INT>, std::SR_allocator<INT> > IntAttrRefreshArray;

typedef std::map< int, CItemBoxRef*, std::less<int>, std::SR_allocator< std::pair< const int, CItemBoxRef* > > > RefIdMap;

 

namespace std {
 template <class _Ty>
 class SR_allocator : public _Allocator_base<_Ty>
 {
 public:
  // type definitions
  typedef size_t  size_type;
  typedef ptrdiff_t difference_type;
  typedef _Ty*        pointer;
  typedef const _Ty*  const_pointer;
  typedef _Ty&        reference;
  typedef const _Ty&  const_reference;
  typedef _Ty         value_type;

  // rebind SR_allocator to type U
  template <class U>
  struct rebind {
   typedef SR_allocator<U> other;
  };

  // return address of values
  pointer address (reference value) const {
   return &value;
  }
  const_pointer address (const_reference value) const {
   return &value;
  }

  /* constructors and destructor
  * - nothing to do because the SR_allocator has no state
  */
  SR_allocator() throw() {
  }
  SR_allocator(const SR_allocator&) throw() {
  }
  template <class U>
  SR_allocator (const SR_allocator<U>&) throw() {
  }
  ~SR_allocator() throw() {
  }

  // return maximum number of elements that can be allocated
  size_type max_size () const throw() {
   return numeric_limits<size_t>::max() / sizeof(_Ty);
  }

  // allocate but don't initialize num elements of type T
  pointer allocate (size_type num,
   allocator<void>::const_pointer hint = 0) {
    // allocate memory with memory pool
    return (pointer)( CSmallObject_Allocator<true>::instance().allocate(num*sizeof(_Ty)) );
  }

  // initialize elements of allocated storage p with value value
  void construct (pointer p, const _Ty& value) {
   // initialize memory with placement new
   new((void*)p)_Ty(value);
  }

  // destroy elements of initialized storage p
  void destroy (pointer p) {
   // destroy objects by calling their destructor
   p->~_Ty();
  }

  // deallocate storage p of deleted elements
  void deallocate (pointer p, size_type num) {
   // deallocate memory with memory pool
   CSmallObject_Allocator<true>::instance().deallocate(p, num*sizeof(_Ty) );
  }
 };

 // return that all specializations of this SR_allocator are interchangeable
 template <class T1, class T2>
 bool operator== (const SR_allocator<T1>&,
  const SR_allocator<T2>&) throw() {
   return true;
 }
 template <class T1, class T2>
 bool operator!= (const SR_allocator<T1>&,
  const SR_allocator<T2>&) throw() {
   return false;
 }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值