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[]
相关推荐
kylezhao20194 分钟前
C# 中实现自定义的窗口最大化、最小化和关闭按钮
开发语言·c#
一苓二肆11 分钟前
PUMA机械臂matlab仿真正逆解与路径规划
开发语言·matlab
Frank_refuel15 分钟前
C++之继承
开发语言·c++
sunfove36 分钟前
Python 自动化实战:从识图点击、模拟真人轨迹到封装 EXE 全流程教学
开发语言·python·自动化
傻啦嘿哟37 分钟前
Python网页自动化操作全攻略:从入门到实战
开发语言·python·自动化
哪有时间简史42 分钟前
C++程序设计
c++
sycmancia42 分钟前
C语言学习06——函数的定义
c语言
定偶1 小时前
Linux进程管理和进程间通信机制
c语言·进程·共享内存·管道·信号量·消息列队
筱歌儿1 小时前
TinyMCE-----word表格图片进阶版
开发语言·javascript·word
黎雁·泠崖1 小时前
Java面向对象:对象数组进阶实战
java·开发语言