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[]
相关推荐
爱编码的小八嘎9 分钟前
C语言完美演绎4-10
c语言
傻啦嘿哟18 分钟前
Python 操作 Excel 条件格式指南
开发语言·python·excel
逆境不可逃19 分钟前
LeetCode 热题 100 之 33. 搜索旋转排序数组 153. 寻找旋转排序数组中的最小值 4. 寻找两个正序数组的中位数
java·开发语言·数据结构·算法·leetcode·职场和发展
tankeven22 分钟前
HJ137 乘之
c++·算法
星空下的月光影子32 分钟前
易语言开发从入门到精通:进阶篇·数据处理与分析自动化·高频刚需手工转自动场景全覆盖
开发语言
林夕sama34 分钟前
多线程基础(四)
java·开发语言
Yang-Never38 分钟前
ADB ->adb shell perfetto 抓取 trace 指令
android·开发语言·adb·android studio
小鸡吃米…42 分钟前
Python 网络爬虫 —— 环境设置
开发语言·爬虫·python
add45a1 小时前
C++中的观察者模式
开发语言·c++·算法