Created
November 15, 2011 04:16
-
-
Save BourneID/1366118 to your computer and use it in GitHub Desktop.
Automatically release memeory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* MAutoReleasePointer.h release memory automatically | |
* | |
* Created on: 2011-10-27 | |
* Author: bourneli | |
*/ | |
#ifndef MSMARTPOINTER_H_ | |
#define MSMARTPOINTER_H_ | |
/** | |
* DemoCode: | |
void aFuntion() | |
{ | |
Object* ptr = CreateObject(); | |
MAutoReleasePointer<Object> pArp(ptr); // delete ptr when get out of the scope | |
... | |
ptr->FuntionWouldThrowException(); | |
... | |
AFunctionMightThrowException(ptr); | |
... | |
// pArp will delete ptr automatically | |
} | |
*/ | |
template <class T> | |
class MAutoReleasePointer | |
{ | |
private: | |
const T* m_p; // pointer for the memory | |
private: | |
/** | |
* no copying constructing | |
*/ | |
MAutoReleasePointer(const MAutoReleasePointer& pRhs) {} | |
/** | |
* no operator = | |
*/ | |
void operator = (const MAutoReleasePointer& pRhs) {} | |
public: | |
/** | |
* constructor for const | |
*/ | |
MAutoReleasePointer(const T* p) : m_p(p) {} | |
/** | |
* constructor | |
*/ | |
MAutoReleasePointer(T* p) : m_p(p) {} | |
/** | |
* delete the memory in desctructor | |
*/ | |
~MAutoReleasePointer() {delete m_p;} | |
}; | |
#endif /* MSMARTPOINTER_H_ */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment