平常我们在使用malloc申请内存时,频繁的申请小块内存会造成内存的浪费,所以可以使用内存池来减少内存的浪费。
memory_pool.h
#ifndef MEMORY_POOL
#define MEMORY_POOL
#include <iostream>
#define size 20
#define numsize 10
class freenode
{
public:
char data[size];
struct obj
{
struct obj *next;
};
};
class memblock
{
public:
freenode data[numsize];
memblock *next;
};
class mem_pool
{
public:
mem_pool();
~mem_pool();
void* malloc(int m_size);
void free(void* p);
private:
freenode *nodehead;
memblock *blockhead;
};
#endif
memory_pool.cpp
#include "memory_pool.h"
mem_pool::mem_pool()
{
nodehead = NULL;
blockhead = NULL;
}
mem_pool::~mem_pool()
{
memblock* temp = NULL;
while(blockhead != NULL)
{
temp = blockhead;
blockhead = blockhead->next;
delete temp;
temp = NULL;
}