码迷,mamicode.com
首页 > 其他好文 > 详细

简单的ALloctor模板

时间:2016-12-22 14:36:24      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:cto   template   nbsp   type   oct   大小   简单   blog   style   

RT,只能分配固定大小内存的分配器,优点是分配回收只要O(1)

template <typename T>class Alloctor{
private:
    typedef T* address;
    T *memory;
    size_t total_size;
public:
    Alloctor(size_t size = 120) :memory(NULL),total_size(size){
        assert(sizeof(T) >= 4);
        memory = (address)malloc(total_size*sizeof(T));
        void * buf;
        for (size_t  i = 0; i < total_size - 1; i++){
            buf = (void*)(memory + i + 1);
            memcpy(memory + i, &buf,sizeof(void*));
        }
        buf = NULL;
        memcpy(memory+total_size-1,&buf,sizeof(void*));
    }
    address alloc(){
        address res;
        memcpy(&res, memory, sizeof(void*));
        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(memory);
    }
};

 

简单的ALloctor模板

标签:cto   template   nbsp   type   oct   大小   简单   blog   style   

原文地址:http://www.cnblogs.com/Dadio/p/6210775.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!