#include "xiCore/Object.h"
#include <cstdio>
class Sample : public xi::Object
{
int blah;
};
typedef xi::Pointer<Sample> SamplePtr;
void test(xi::ObjectPtr s)
{
}
int main(void)
{
SamplePtr sample = new Sample();
xi::ObjectPtr object = sample;
object = 0;
object = sample;
test(sample);
return 0;
}
#ifndef XI_POINTER_H
#define XI_POINTER_H
namespace xi
{
// A smart pointer. Type T should subclass Object.
template <typename T>
class Pointer
{
public:
Pointer(T* p = 0) : mPtr(p)
{
if(mPtr != 0)
mPtr->addRef();
}
Pointer(const Pointer<T>& cp)
{
Pointer<T>& p = const_cast<Pointer<T>&>(cp);
mPtr = p.get();
if(mPtr != 0)
mPtr->addRef();
}
template <typename T2>
Pointer(const Pointer<T2>& cp)
{
Pointer<T2>& p = const_cast<Pointer<T2>&>(cp);
mPtr = reinterpret_cast<T*>(p.get());
if(mPtr != 0)
mPtr->addRef();
}
~Pointer(void)
{
if(mPtr != 0)
mPtr->removeRef();
}
bool valid(void) const
{
return (mPtr != 0);
}
Pointer<T>& operator=(T* p)
{
reset(p);
return *this;
}
Pointer<T>& operator=(Pointer<T>& p)
{
reset(p.get());
return *this;
}
template <typename T2>
Pointer<T>& operator=(const Pointer<T2>& cp)
{
Pointer<T2>& p = const_cast<Pointer<T2>&>(cp);
reset(p.get());
return *this;
}
template <typename T2>
Pointer<T>& operator=(T2* p)
{
reset(p);
return *this;
}
T& operator*(void) const
{
return *mPtr;
}
T* operator->(void) const
{
return mPtr;
}
T* get(void) const
{
return mPtr;
}
//operator T*(void) const
//{
// return mPtr;
//}
void release(void)
{
if(mPtr != 0)
mPtr->removeRef();
mPtr = 0;
}
void reset(T* p = 0)
{
if(mPtr != 0)
mPtr->removeRef();
mPtr = p;
if(mPtr != 0)
mPtr->addRef();
}
template <typename T2>
operator Pointer<T2>(void)
{
return Pointer<T2>(*this);
}
private:
T* mPtr;
};
}
#endif
#ifndef XI_OBJECT_H
#define XI_OBJECT_H
#include "Common.h"
#include "Pointer.h"
namespace xi
{
// This is the root class for all objects in the engine. For now it just
// provides reference counting for smart pointers. In the future, it can be
// used for object tracking, memory tracking, RTTI, etc. In general, objects
// should be managed with the Pointer smart pointer.
class Object
{
public:
virtual ~Object(void) = 0;
void addRef(void) {++mRefCount;}
void removeRef(void)
{
if (--mRefCount <= 0)
delete this;
}
protected:
Object(void) : mRefCount(0) {}
private:
s32 mRefCount;
};
inline Object::~Object(void) {}
typedef Pointer<Object> ObjectPtr;
}
#endif