#include <new>
#include <stdio.h>
#include <stdlib.h>
#ifndef NULL
#define NULL 0
#endif
//!内存分配.封装operator new函数
template <typename T>
T *allocate(size_t n,T*)
{
T *tmp = (T*) operator new(n * sizeof(T));
if (tmp == NULL)
{
fprintf(stderr,"Memory allocate error");
exit(1);
}
return tmp;
}
//!封装 operator delete函数
template <typename T>
void deallocate(T *p)
{
return operator delete((void *)p);
}
//!在p所指向的内存中用value值构造对象
template <typename T>
T *construct(T *p,const T &value)
{
return (T*)new (p) T(value);
}
//!析构p指向的对象,但不释放内存
template <typename T>
void destroy(T *p)
{
p->~T();
}
//!一个简单的空间配置器
template <typename T>
class allocator
{
//!内部类型的定义
typedef size_t size_type;
typedef T value_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
public:
allocator();
~allocator();
pointer allocate(size_type n);
void deallocate(pointer p);
void construct(pointer p,const_reference value);
void destroy(pointer p);
};
template <typename T>
allocator<T>::allocator()
{
}
template <typename T>
allocator<T>::~allocator()
{
}
//!内存分配
template<typename T>
typename T* allocator<T>::allocate(size_type n)
{
return ::allocate(n,(pointer)0);
}
//!内存回收
template<typename T>
void allocator<T>::deallocate(pointer p)
{
return ::deallocate(p);
}
//!对象构造
template<typename T>
void allocator<T>::construct(pointer p,const_reference value)
{
::construct(p,value);
}
//!对象析构
template<typename T>
void allocator<T>::destroy(pointer p)
{
::destroy(p);
}
//测试程序
#include "allocator.h"
int main()
{
allocator<int> alloc;
int *p = alloc.allocate(1);
alloc.construct(p,10);
alloc.destroy(p);
alloc.deallocate(p);
return 0;
}