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; }