namespace Neon
{
template<class T>
class SmartPtr
{
private:
T *ptr;
mutable volatile long *count;
public:
const long refcount()
{
return *this->count;
}
void addref() const
{
if (count == 0)
{
return;
}
XInterlockedIncrement(count);
}
void deref()
{
if (count == 0)
{
return;
}
if (XInterlockedDecrement(count) == 0)
{
delete count;
delete ptr;
}
}
void init(T *ptr, volatile long *count)
{
this->ptr = ptr;
this->count = count;
}
SmartPtr(T *ptr_p, volatile long *count)
{
init(ptr_p, count);
this->addref();
}
SmartPtr()
{
long *count_p;
count_p = new long;
*count_p = 1;
init((T *)0, count_p);
}
SmartPtr(T *ptr_p)
{
long *count_p;
count_p = new long;
*count_p = 1;
init(ptr_p, count_p);
}
SmartPtr(const SmartPtr<T>& ptr)
{
this->init(ptr.ptr, ptr.count);
this->addref();
}
template <typename U>
SmartPtr<U> reinterpret()
{
SmartPtr<U> retval;
retval.init((U *)this->ptr, this->count);
retval.addref();
return retval;
}
~SmartPtr()
{
deref();
}
inline operator T *()
{
return ptr;
}
inline T *operator&()
{
return ptr;
}
inline T *operator->()
{
return ptr;
}
inline bool operator==(const SmartPtr<T> &ptr)
{
return ptr.ptr == this->ptr;
}
inline bool operator==(const T *ptr_p)
{
return ptr_p == ptr;
}
inline bool operator!=(const SmartPtr<T> &ptr)
{
return ptr.ptr != this->ptr;
}
inline bool operator!=(const T *ptr_p)
{
return ptr_p != ptr;
}
inline void operator=(const T *ptr_p)
{
long *count_p;
deref();
count_p = new long;
*count_p = 1;
init(ptr_p, count_p);
}
inline void operator=(const SmartPtr<T> &ptr)
{
ptr.addref();
deref();
init(ptr.ptr, ptr.count);
}
};
}