简单的ALloctor模板

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);
}
};

上一篇:php socket通过smtp发送邮件(纯文本、HTML,多收件人,多抄送,多密送)


下一篇:百度云曲显平:AIOps时代下如何用运维数据系统性地解决运维问题?