I am currently reading the "3D Game Engine Architecture" book by David H. Eberly, and decided to implement my own little reference counting smart pointer. I have mostly followed his implementation, but I am experiencing a problem with my implementation.
I created a function called 'CreateRef' which returns a Pointer. All is well when I use this function in the same scope as the object I have created, but the moment I put the object in the global scope it destroys the object right after creation.
class Object
{
public:
void IncrementReferences()
{
++m_References;
}
void DecrementReferences()
{
if(--m_References == 0) delete this;
}
int GetReferenceCount() const { return m_References; }
private:
int m_References = 0;
};
template<class T>
class Pointer
{
public:
//costr and destr
Pointer(T* pObject = nullptr)
{
m_pObject = pObject;
if (m_pObject)
m_pObject->IncrementReferences();
}
Pointer(const Pointer& rPointer)
{
m_pObject = rPointer.m_pObject;
if (m_pObject)
m_pObject->IncrementReferences();
}
~Pointer()
{
if (m_pObject)
m_pObject->DecrementReferences();
}
// implicit conversions
operator T* () const
{
return m_pObject;
}
T& operator* () const
{
return *m_pObject;
}
T* operator-> () const
{
return m_pObject;
}
// Assignment
Pointer& operator= (T* pObject)
{
if (m_pObject != pObject)
{
if (pObject)
pObject->IncrementReferences();
if (m_pObject)
m_pObject->DecrementReferences();
m_pObject = pObject;
}
return *this;
}
Pointer& operator= (const T* rReference)
{
if (m_pObject != rReference)
{
if (rReference)
rReference->IncrementReferences();
if (m_pObject)
m_pObject->DecrementReferences();
m_pObject = rReference;
}
return *this;
}
// Comparisons
bool operator== (T* pObject) const { return m_pObject == pObject; }
bool operator!= (T* pObject) const { return m_pObject != pObject; }
bool operator== (const Pointer& rReference) const { return m_pObject == rReference.m_pObject; }
bool operator!= (const Pointer& rReference) const { return m_pObject != rReference.m_pObject; }
protected:
// The shared object
T* m_pObject;
};
template<typename T>
using Ref = Pointer<T>;
template<typename T, typename ...Args>
constexpr Ref<T> CreateRef(Args&&... args)
{
return Ref<T>(new T(args...));
}
Main
static Ref<Person> person = nullptr; // Doesn't work like this
static void DoSomething()
{
person = CreateRef<Person>("Name");
std::cout << "References " << person->GetReferenceCount() << std::endl;
Ref<Person> newPerson = person;
std::cout << "References " << newPerson->GetReferenceCount() << std::endl;
}
int main()
{
DoSomething();
std::cout << person->GetReferenceCount();
}
I have a feeling I am doing something wrong with the 'Pointer' class but I can't quite understand what I am missing.