使用起来很简单,像这样:
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;
}
}