GLProgramming.com

home :: about :: development guides :: irc :: forums :: search :: paste :: links :: contribute :: code dump

-> Click here to learn how to get live help <-


New Paste :: Recent Pastes:: No Line Numbers


"smart" pointers by baldurk
1
 
class MMObject
{
  public:
    MMObject() { objects.push_back(this); }
    void AddRef() { ++refcount; }
    void Release() { --refcount; }

    static bool CollectGarbage()
    {
    vector<MMObject *>::iterator new_end =
    remove_if(objects.begin(), objects.end(), dead);
    objects.erase(new_end, objects.end());
    }

    static bool num() { return objects.size(); }
  private:
    static bool dead(MMObject *o)
    {
    if(o->refcount == 0)
        return true;

    return false;
    }

    static vector<MMObject *> objects;
    int refcount;
};


template <class T> class Pointer
{
  public:
    Pointer() { obj = NULL; }
    Pointer(T *o) { obj = NULL; *this = o; }
    Pointer(Pointer<T> o) { obj = NULL; *this = o; }
    Pointer(Pointer<T> &o) { obj = NULL; *this = o; }
    ~Pointer() { if(obj) obj->Release(); }

    operator T*() const { return obj; }

    bool operator !() const { return !obj; }
    bool operator ==(Pointer<T> o) const { return obj == o.obj; }
    bool operator ==(T *o) const { return obj == o; }

    T &operator *() const { assert(obj!=NULL);return *obj; }
    T *operator ->() const { assert(obj!=NULL);return obj; }

    void operator =(T *o)
    {
    if(obj) obj->Release();
    obj = o;
    if(obj) obj->AddRef();
    }

    void operator =(Pointer<T> o)
    {
    if(obj) obj->Release();
    obj = o.obj;
    if(obj) obj->AddRef();
    }
  private:
    T *obj;
};


/////////////////////////////////////////////////////////////

struct Int : public MMObject
{
  public:
    int i;
    operator int() { return i; }
};

Pointer<Int> PI = new Int();