c++ 固定分配大小的简单内存池

最近学习stl源码编程,一直想自己实现一个内存池,恰好前段时间2015阿里实习笔试有一道内存池的题目,将代码写在这里了。

//
// Created by ma on 2015/6/28.
//

#ifndef MEMORYPOOL_H_
#define MEMORYPOOL_H_
#include 

typedef enum M_P_SIZE{
 INIT_SIZE=16,
 ADD_BUFF_SIZE=32
}M_P_SIZE;

class MemoryPool {
public:
    MemoryPool(size_t buff_size=1,size_t freesize=INIT_SIZE);
    ~MemoryPool();
    void *allocate();
    void deallocate(void *p);
    size_t chuck(const size_t n);

    size_t get_free_buff_size() const { return free_buffer_size;}
    size_t get_total_buff_size() const    { return total_buff_size;}

private:
    typedef union node{
        void *data;
        node* next;
    }node;
    size_t free_buffer_size;
    size_t total_buff_size;
    node* free_start;
    size_t buff_size;
};
#endif //MEMORYPOOL_H_
//
// Created by ma on 2015/6/28.
//

#include 
#include "MemoryPool.h"

void *MemoryPool::allocate() {
    if(free_buffer_size <=0)
    {
        size_t n= total_buff_size > ADD_BUFF_SIZE ? total_buff_size >>1 : INIT_SIZE;
        size_t res=chuck(n);
        if(res==0)
            return NULL;
        free_buffer_size =res;
        total_buff_size +=res;
    }

    void *data=free_start;
    free_start=free_start->next;
    free_buffer_size--;

    return data;
}


void MemoryPool::deallocate(void *p) {
    node* q=(node*)p;
    q->next=free_start;
    free_start=q;
    free_buffer_size++;

}
MemoryPool::~MemoryPool() {
    while (free_start)
    {
        node* p=free_start;
        free_start=free_start->next;
        free(p);
    }

}
MemoryPool::MemoryPool(size_t buff_size, size_t freesize):free_start(NULL){

    size_t least_buf_size=sizeof(node);
    this->buff_size = buff_size>least_buf_size?buff_size:least_buf_size;

    size_t res = chuck(freesize);
    total_buff_size = res;
    free_buffer_size = res;

}
size_t MemoryPool::chuck(const size_t n) {
    for (size_t i=0;iif(pnode==NULL)
            return i;
        pnode->next=free_start;
        free_start=pnode;
    }

}

随后附上一段小测试代码,验证正确运行。

#include 
#include "MemoryPool.h"
#include "vector"
using namespace std;
int main()
{
    vector<int* > i_vec;
    MemoryPool *m_pool=new MemoryPool(sizeof(int),16);

    for(size_t i=0;i<100;i++) {
        int *a = (int *) (m_pool->allocate());
        *a=(int)i;
        i_vec.push_back(a);
    }

    cout<<"free_buff_size="<get_free_buff_size()<cout<<"total_buff_size="<get_total_buff_size()<for(size_t i=0;i<30;i++) {
        int *p=i_vec.back();
        cout<<*p<<'\t';
        i_vec.pop_back();

        m_pool->deallocate(p);
    }

    cout<<"free_buff_size="<get_free_buff_size()<cout<<"total_buff_size="<get_total_buff_size()<~MemoryPool();

    cout<<"end"<

你可能感兴趣的:(c)