#ifndef __autil_refcount__
#define __autil_refcount__

namespace autil {

  // This refrence count implemnation is NOT thread safe
  // nor does it handle cyclic refrences.

  template <typename Class> 
  class RefCount {
    struct Data {
      Class data;
      int   count;
      Data() : count(1) {}
      Data(const Class & d) : data(d), count(1) {}
    };
    Data * data;
    void inc() {
      ++(data->count);
    }
    void dec() {
      --(data->count);
      if (data->count == 0) 
	delete data;
    }
  public:

    RefCount() 
      : data(new Data()) {}
    
    RefCount(const Class & d) 
      : data(new Data(d)) {}

    RefCount(const RefCount & other) 
      : data(other.data) {inc();}

    RefCount & operator= (const RefCount & other) {
      if (data == other.data) return *this;
      dec();
      data = other.data;
      inc();
      return *this;
    }

    Class * ptr() const {return &data->data;}
    Class & operator *  ()const  {return data->data;}
    Class * operator-> () const {return &data->data;}
    
    ~RefCount() {dec();}
  };

}

#endif

