c++ 重载new和delete实现内存管理

本文探讨了如何在C++中通过重载new和delete操作符来实现自定义的内存管理策略。通过重载,我们可以定制内存分配和释放的行为,比如跟踪内存使用情况、实现内存池等高级内存管理技术。了解这一技巧对于优化程序性能和避免内存泄漏至关重要。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <stdlib.h>
using namespace std;
//全局的new delete监视所有内存释放分配
//局部的new delete监视某个类的所有分配释放

void* operator new(size_t size)
{
    if (size == 0)
    {
        return 0;
    }
    void* p = malloc(size);
    cout << "全局被调用内存被分配" << p << endl;
    return p;
}

void operator delete(void* p)
{
    cout << "全局被调用内存被释放" << p << endl;
    free(p);
}

void* operator new[](size_t size)
{
    return operator new(size);
}

void operator delete[](void* p)
{
    return operator delete(p);
}

class myclass
{
public:
    static int result;
    int* p;
    int length;
public:
    myclass()
    {
        cout << "myclass被创建" << endl;
    }
    ~myclass()
    {
        cout << "myclass被销毁" << endl;
    }
    //类的内部new没有完成分配内存的动作,只是通往全局new中间做了一个劫持
    static void* operator new(size_t size)
    {
        result += 1;
        cout << "对象被创建" << endl;
        myclass *ptemp = ::new myclass;//劫持
        return ptemp;//返回一个全局的指针
    }
    static void* operator new[](size_t size)
    {
        cout << "对象数组被创建" << endl;
        return operator new(size);  //每个对象挨个调用已经重载好的new
    }
    static void operator delete(void* p)
    {
        result -= 1;
        cout << "对象被销毁" << endl;
        ::delete p;
    }
    static void operator delete[](void* p)
    {
        cout << "对象数组被销毁" << endl;
        return operator delete(p);
    }
};

int myclass::result = 0;

void main()
{
    //int* p = new int[10];
    //delete[] p;
    myclass *p1 = new myclass[5];
    delete[] p1;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值