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[]
相关推荐
czhaii2 分钟前
单片机最佳入门多线程示例讲解
c语言·单片机
1尢晞14 分钟前
Java学习
java·开发语言
毕设源码-赖学姐12 分钟前
【开题答辩全过程】以 基于python的电影推荐系统为例,包含答辩的问题和答案
开发语言·python
星辰_mya17 分钟前
Elasticsearch线上问题之慢查询
java·开发语言·jvm
Yu_Lijing19 分钟前
网络复习篇——网络基础(一)
网络·c++·笔记
前端小菜袅20 分钟前
PC端原样显示移动端页面方案
开发语言·前端·javascript·postcss·px-to-viewport·移动端适配pc端
Bella的成长园地20 分钟前
为什么c++中的条件变量的 wait() 函数需要配合while 循环或谓词?
c++·面试
Highcharts.js21 分钟前
如何使用Highcharts SVG渲染器?
开发语言·javascript·python·svg·highcharts·渲染器
charlee4422 分钟前
为什么现代 C++ 库都用 PIMPL?一场关于封装、依赖与安全的演进
c++·智能指针·raii·pimpl·编译防火墙·封装设计
郝学胜-神的一滴26 分钟前
超越Spring的Summer(一): PackageScanner 类实现原理详解
java·服务器·开发语言·后端·spring·软件构建