C/C++中实现自定义自动释放堆内存空间类

一.自动释放堆内存空间类 CAutofree.h

cpp 复制代码
#ifndef TESTAUTOFREE_CAUTOFREE_H
#define TESTAUTOFREE_CAUTOFREE_H
#include <iostream>
using namespace std;
// To free the instance in the current scope, for instance, MyClass* ptr,
// which is a ptr and this class will:
//       1. free the ptr.
//       2. set ptr to NULL.
//
// Usage:
//       MyClass* po = new MyClass();
//       // ...... use po
//       SrsAutoFree(MyClass, po);
//
// Usage for array:
//      MyClass** pa = new MyClass*[size];
//      // ....... use pa
//      SrsAutoFreeA(MyClass*, pa);
//
// @remark the MyClass can be basic type, for instance, SrsAutoFreeA(char, pstr),
//      where the char* pstr = new char[size].
// To delete object.
#define CAutoFree(className, instance) \
impl_CAutoFree<className> _auto_free_##instance(&instance, false, false)
// To delete array.
#define CAutoFreeA(className, instance) \
impl_CAutoFree<className> _auto_free_array_##instance(&instance, true, false)
// Use free instead of delete.
#define CAutoFreeF(className, instance) \
impl_CAutoFree<className> _auto_free_##instance(&instance, false, true)
// The template implementation.
template<class T>
class impl_CAutoFree
{
private:
    T** ptr;
    bool is_array;
    bool _use_free;
public:
    // 禁止拷贝
    impl_CAutoFree(const impl_CAutoFree&) = delete;
    impl_CAutoFree& operator=(const impl_CAutoFree&) = delete;

    // If use_free, use free(void*) to release the p.
    // Use delete to release p, or delete[] if p is an array.
    impl_CAutoFree(T** p, bool array, bool use_free) {
        ptr = p;
        is_array = array;
        _use_free = use_free;
    }
    virtual ~impl_CAutoFree() {
        if (ptr == NULL || *ptr == NULL) {
            return;
        }

        if (_use_free) {
            printf("~impl_CAutoFree ~~ use_free\n");
            free(*ptr);
        } else {
            if (is_array) {
                printf("~impl_CAutoFree ~~ use_delete[]\n");
                delete[] *ptr;
            } else {
                printf("~impl_CAutoFree ~~use delete\n");
                delete *ptr;
            }
        }

        *ptr = NULL;
    }
};
#endif //TESTAUTOFREE_CAUTOFREE_H

二.Demo应用

cpp 复制代码
#include <cstring>
#include <iostream>

#include "CAutofree.h"
struct UserInfo {
    string name;
    string department;
    string age;
    string phone;
};// TIP 要<b>Run</b>代码,请按 <shortcut actionId="Run"/> 或点击装订区域中的 <icon src="AllIcons.Actions.Execute"/> 图标。
int main() {
    char* arr = new char[100];
    CAutoFreeA(char,arr);

    void* arr2 = malloc(100);
    CAutoFreeF(void,arr2);

    UserInfo *user = new UserInfo;
    user->name = "bruce";
    user->department = "HR";
    user->age = "28";
    user->phone = "xxx";
    CAutoFree(UserInfo,user);

    memcpy(arr,"hello world",100);
    memcpy(arr2,"hello world 222",100);

    printf("str = %s\n",arr);
    printf("str2 = %s\n",arr2);
    printf("user.name = %s user.department =%s user.age = %s user.phone =%s\n",
        user->name.c_str(),user->department.c_str(),user->age.c_str(),user->phone.c_str());
    return 0;// TIP 请访问 <a href="https://www.jetbrains.com/help/clion/">jetbrains.com/help/clion/</a> 查看 CLion 帮助。此外,您还可以从主菜单中选择"帮助 | 学习 IDE 功能",尝试 CLion 的交互式课次。
}

三.运行结果

cpp 复制代码
str = hello world
str2 = hello world 222
user.name = bruce user.department =HR user.age = 28 user.phone =xxx
~impl_CAutoFree ~~use delete
~impl_CAutoFree ~~ use_free
~impl_CAutoFree ~~ use_delete[]
相关推荐
薇茗1 分钟前
【初阶数据结构】 升沉有序的平仄 排序 3
c语言·开发语言·数据结构·算法·排序算法·文件归并排序
字节高级特工3 分钟前
C++11(一) 革新:右值引用与移动语义
java·开发语言·c++·人工智能·后端
孬甭_3 分钟前
双向链表详解
c语言·数据结构·链表
薇茗3 分钟前
【初阶数据结构】 升沉有序的平仄 排序 2
c语言·数据结构·算法·排序算法·快排精讲
安生生申5 分钟前
uni-app 连接 JDY-31 蓝牙串口模块实践
c语言·前端·javascript·stm32·单片机·嵌入式硬件·uni-app
叶之香6 分钟前
一次 Kingston U 盘重定向中获取 Device Descriptor 超时问题排查
c++·windows·visual studio
UestcXiye6 分钟前
GoogleTest 使用指南 | 单元覆盖率分析
c++·单元测试·googletest
AI科技星8 分钟前
强哥德巴赫猜想(1+1)终极证明(2026 年5月 21 日)
开发语言·人工智能·算法·计算机视觉·量子计算
王老师青少年编程10 分钟前
csp信奥赛C++高频考点专项训练之前缀和&差分 --【一维前缀和】:“非常男女”计划
c++·前缀和·csp·高频考点·信奥赛·“非常男女”计划
番茄灭世神11 分钟前
Vscode开发/调试ARM单片机最新教程
c语言·arm开发·vscode·stm32·嵌入式·gd32