自定义实现内存池

内存池:
1.创建一个结构体管理内存池。
2.重载new和delete操作符
3.执行new时,“先执行重载new操作符函数”,再执行“构造函数”!!
4.执行delete时,“先执行虚构函数”,再执行“重载delete操作符函数”

代码:
struct ST_MemoryPool
{
char* pStart; //总内存块的起始位置
char* pUseStart; //使用时的位置
int totalSize; //内存大小
int useSize; //已使用大小

ST_MemoryPool(int size)
{
    totalSize = size;
    useSize = 0;
    pStart = (char*)malloc((totalSize) * sizeof(char)); 
    pUseStart = pStart;

    cout << "构造函数: size: " << totalSize << endl;
}

~ST_MemoryPool()
{
    cout << "执行析构函数" << endl;
    if (pStart)
    {
        free(pStart);
        pStart = NULL;
        pUseStart = NULL;
        totalSize = 0;
        useSize = 0;

        cout << "释放内存池内存 " << endl;
    }
}

void UsingSize(int n)
{
    if (useSize+n > totalSize)
    {
        assert(useSize + n <= totalSize);
        return;
    }

    pUseStart = pUseStart + n;
    useSize += n;
}

void* operator new(size_t size)
{
    if (size <= 0)
    {
        return NULL;
    }

    cout << "new分配内存: " << sizeof(ST_MemoryPool) * sizeof(char) << endl;
    return (void*)malloc(sizeof(ST_MemoryPool) * sizeof(char));
}

void operator delete(void* st)
{
    if (st == NULL)
    {
        return;
    }

    free(st);
    st = NULL;
    cout << "delete释放结构体内存 " << endl;
}

};

int main()
{
ST_MemoryPool* st_mp = new ST_MemoryPool(1024);
cout << “st_mp.totalSize: ” << st_mp->totalSize << endl;
int* a = (int*)(st_mp-> pUseStart);
*a = 200;
st_mp->UsingSize(100);
float* b = (float*)(st_mp->pUseStart);
*b = 1000;
st_mp->UsingSize(300);

double* c = (double*)(st_mp->pUseStart);
*c = 1500;
st_mp->UsingSize(600);

int* aa = (int*)(st_mp->pStart);
cout << "aa: " << *aa << endl;

float* bb = (float*)(st_mp->pStart+100);
cout << "bb: " << *bb << endl;

double* cc = (double*)(st_mp->pStart + 100+300);
cout << "cc: " << *cc << endl;

delete st_mp;
system("pause");

return 0;

}

运行结果:
这里写图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值