// -*-c++-*-
#ifndef RCPOINTER_H
#define RCPOINTER_H

#include <stdlib.h>

template <typename T>
class RcPointer
{
public:
    RcPointer(T *p = 0) : m_p(p)
    {
        m_refcount = new size_t;
        *m_refcount = 1;
    }
    
    RcPointer(const RcPointer<T> &other)
        : m_p(other.m_p), m_refcount(other.m_refcount)
    {
        (*m_refcount)++;
    }
    
    inline void Destroy()
    {
        (*m_refcount)--;
        if (*m_refcount == 0)
        {
            delete m_refcount;
            delete m_p;
        }
    }

    ~RcPointer()
    {
        Destroy();
    }

	
    inline T* operator->() { return m_p; }
    inline const T* operator->() const { return m_p; }
	
    inline T& operator*() { return *m_p; }
    inline const T& operator*() const { return *m_p; }
	
    RcPointer<T>& operator=(const RcPointer &other)
    {
        if (&other != this)
        {
            Destroy();
            m_p = other.m_p;
            m_refcount = other.m_refcount;
            (*m_refcount)++;
        }
        return *this;
    }
	
private:
    T   *m_p;
    mutable size_t *m_refcount;
    	
};

#endif
