zoukankan      html  css  js  c++  java
  • C++数组和对象空间自动释放(AutoRelease)

    C++数组和对象空间自动释放(AutoRelease),可代替goto统一释放申请的空间

    /**
      \file AutoRelease.h
    
      \brief 自动空间释放类,可避免动态申请的空间在多处return时而在某处
             未进行释放造成的错误
    \version 1.0
    */ #ifndef _AUTORELEASE_H_ #define _AUTORELEASE_H_ /** \brief 释放的元素类型 */ typedef enum { AUTORELEASE_ARR, AUTORELEASE_OBJ, }AUTORELEASE_TYPE; template <class Type, const AUTORELEASE_TYPE autoType > class AutoRelease { public: AutoRelease() { } ~AutoRelease() { if ( autoType == AUTORELEASE_ARR ) { delete[] m_elem; } else if ( autoType == AUTORELEASE_OBJ ) { delete m_elem; } } AutoRelease( Type &elem) : m_elem(elem) { } private: const Type &m_elem; }; #endif

    示例程序

    #include "AutoRelease.h"
    
    #include <windows.h>
    
    #include <iostream>
    using namespace std;
    
    class Test
    {
    public:
        Test()
        {
    
        }
    
        ~Test()
        {
    
        }
    
    private:
        char arr[1024*10];
    };
    
    void FuncNew()
    {
        Test *p = new Test();
        AutoRelease<Test *,AUTORELEASE_OBJ> autoRelease(p);
        if ( p == NULL ) 
        {
            return;
        }
    }
    
    int main()
    {
        while (1)
        {
            FuncNew();
            Sleep(1000);
        }
        return 0;
    }
  • 相关阅读:
    使用过滤器解决JSP页面的乱码问题
    六度空间(MOOC)
    navicat连接mysql出现1251错误
    Saving James Bond
    列出连通集(mooc)
    File Transfer(并查集)
    堆中的路径(MOOC)
    智慧树mooc自动刷课代码
    Hibernate三种状态的区分。
    Hibernate中get和load方法的区别
  • 原文地址:https://www.cnblogs.com/shanwenbin/p/2853573.html
Copyright © 2011-2022 走看看