Skip to content

Instantly share code, notes, and snippets.

@BourneID
Created November 15, 2011 04:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BourneID/1366118 to your computer and use it in GitHub Desktop.
Save BourneID/1366118 to your computer and use it in GitHub Desktop.
Automatically release memeory
/*
* 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