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[]
相关推荐
端平入洛18 小时前
delete又未完全delete
c++
祈安_1 天前
C语言内存函数
c语言·后端
端平入洛2 天前
auto有时不auto
c++
郑州光合科技余经理3 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1233 天前
matlab画图工具
开发语言·matlab
dustcell.3 天前
haproxy七层代理
java·开发语言·前端
norlan_jame3 天前
C-PHY与D-PHY差异
c语言·开发语言
哇哈哈20213 天前
信号量和信号
linux·c++
多恩Stone3 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ4022054963 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django