Skip to content

Instantly share code, notes, and snippets.

@pluskid
Created April 7, 2012 04:01
Show Gist options
  • Save pluskid/2324946 to your computer and use it in GitHub Desktop.
Save pluskid/2324946 to your computer and use it in GitHub Desktop.
Automatic ref-counting
#ifndef AUTO_PTR_H__
#define AUTO_PTR_H__
template <typename T>
class auto_ptr
{
public:
auto_ptr():m_rawptr(NULL)
{
}
auto_ptr(T *rawptr)
{
init(rawptr);
}
auto_ptr(const auto_ptr<T> &ptr)
{
init(ptr.m_rawptr);
}
auto_ptr<T> &operator=(const auto_ptr<T> &ptr)
{
if (&ptr == this)
return *this;
destroy();
init(ptr.m_rawptr);
return *this;
}
T* operator->()
{
return m_rawptr;
}
const T* operator->() const
{
return m_rawptr;
}
~auto_ptr()
{
destroy();
}
private:
void init(T *rawptr)
{
m_rawptr = rawptr;
m_rawptr->incref();
}
void destroy()
{
if (m_rawptr)
{
m_rawptr->decref();
m_rawptr = NULL;
}
}
T *m_rawptr;
};
#endif // AUTO_PTR_H__
#ifndef SGOBJ_H_6GLKWVOT
#define SGOBJ_H_6GLKWVOT
#include "auto_ptr.h"
#define ENABLE_AUTO_PTR(name) \
friend class auto_ptr<name>; \
typedef auto_ptr<name> ptr; \
typedef const auto_ptr<name> const_ptr
class SGObject
{
public:
ENABLE_AUTO_PTR(SGObject);
virtual ~SGObject()
{
}
protected:
void incref()
{
m_refcnt++;
}
void decref()
{
if (--m_refcnt == 0)
delete this;
}
int m_refcnt;
};
#endif /* end of include guard: SGOBJ_H_6GLKWVOT */
#include <string>
#include <iostream>
#include "sgobj.h"
using namespace std;
class CExample : public SGObject
{
public:
ENABLE_AUTO_PTR(CExample);
CExample(const string& name):m_name(name)
{
cout << name << " constructed" << endl;
}
virtual ~CExample()
{
cout << m_name << " destructed" << endl;
}
const string & name() const
{
return m_name;
}
private:
string m_name;
};
void foo(CExample::const_ptr e)
{
cout << " " << e->name() << " in foo()" << endl;
}
CExample::ptr ex_global;
int main()
{
CExample::ptr ex1 = new CExample("example1");
CExample::ptr ex2 = new CExample("example2");
ex_global = ex2;
foo(ex1);
ex1 = ex1;
ex1 = ex2;
foo(ex1);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment