Skip to content

Instantly share code, notes, and snippets.

@hiroshi
Created February 28, 2011 12:38
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 hiroshi/847260 to your computer and use it in GitHub Desktop.
Save hiroshi/847260 to your computer and use it in GitHub Desktop.
AutoRef.h
#ifndef _AutoRef_h_
#define _AutoRef_h_
/* Example
#include "AutoRef.h"
void AutoRefRelease(CGImageRef ref) { CGImageRelease(ref); }
void someFunction(void) {
AutoRef<CGImage> image = CGImageCreateCopy(src);
// do something...
// you don't need to call
// CGImageRelease(image);
}
*/
template<typename T> void AutoRefRelease(T *ref);
template<typename T> class AutoRef {
public:
AutoRef(T *ref = NULL) : m_ref(ref) {}
~AutoRef() {
if (m_ref) AutoRefRelease(m_ref);
m_ref = NULL;
}
operator T*() const { return m_ref; }
AutoRef& operator=(T *ref) {
if (m_ref) AutoRefRelease(m_ref);
m_ref = ref;
return *this;
}
private:
T *m_ref;
};
#endif //_AutoRef_h_
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment