template <typename T>class Alloctor{
private:
typedef T* address;
T *memory,*t;
size_t total_size;
size_t alignment;
size_t blockSize;
inline void * addressOfBlock(int i){
return (char*)memory + (i)*blockSize;
}
public:
Alloctor(size_t size = 120,size_t align = 4) :memory(NULL),total_size(size),alignment(align){
assert(sizeof(T) >= 4);
size_t pad = (align - (sizeof(T)&(align-1)));
if (pad == align)
pad = 0;
blockSize = pad + sizeof(T);
t = (address)malloc(total_size*(sizeof(T)+pad)+align);
memory = t + (align - (int)t&(align - 1));
void * buf;
for (size_t i = 0; i < total_size - 1; i++){
buf = addressOfBlock(i+1);
memcpy(addressOfBlock(i), &buf, sizeof(void*));
}
buf = NULL;
memcpy(addressOfBlock(total_size-1), &buf, sizeof(void*));
}
address alloc(){
address res;
memcpy(&res, memory, sizeof(void*));
if (res)
memcpy(memory, res, sizeof(void*));
return res;
}
void free(address a){
memcpy(a, memory, sizeof(void*));
void * buf = a;
memcpy(memory,&buf,sizeof(void*));
}
~Alloctor(){
free(t);
}
};