From 9abd4ef04b10d27a7f8087738139798cc389268f Mon Sep 17 00:00:00 2001 From: Josh Holtrop Date: Wed, 4 Jun 2014 21:25:47 -0400 Subject: [PATCH] add jes::Ref template --- src/lib/include/jes/FileReader.h | 3 + src/lib/include/jes/Ref.h | 102 +++++++++++++++++++++++++++++++ src/lib/include/jes/Text.h | 3 + 3 files changed, 108 insertions(+) create mode 100644 src/lib/include/jes/Ref.h diff --git a/src/lib/include/jes/FileReader.h b/src/lib/include/jes/FileReader.h index c24c671..5d16e59 100644 --- a/src/lib/include/jes/FileReader.h +++ b/src/lib/include/jes/FileReader.h @@ -1,6 +1,8 @@ #ifndef JES_FILEREADER_H #define JES_FILEREADER_H +#include "jes/Ref.h" + namespace jes { class FileReader @@ -9,6 +11,7 @@ namespace jes bool load(const char * fname); protected: }; + typedef Ref FileReaderRef; } #endif diff --git a/src/lib/include/jes/Ref.h b/src/lib/include/jes/Ref.h new file mode 100644 index 0000000..9629a38 --- /dev/null +++ b/src/lib/include/jes/Ref.h @@ -0,0 +1,102 @@ +#ifndef JES_REF_H +#define JES_REF_H + +#include + +namespace jes +{ + template + class Ref + { + public: + Ref(); + Ref(T * ptr); + Ref(const Ref & orig); + Ref & operator=(const Ref & orig); + Ref & operator=(T * ptr); + ~Ref(); + T & operator*() const { return *m_ptr; } + T * operator->() const { return m_ptr; } + bool is_null() const { return m_ptr == NULL; } + + private: + void clone_from(const Ref & orig); + void destroy(); + + T * m_ptr; + unsigned int * m_ref_count; + }; + + template + Ref::Ref() + { + m_ptr = NULL; + m_ref_count = NULL; + } + + template + Ref::Ref(T * ptr) + { + m_ptr = ptr; + m_ref_count = new unsigned int; + *m_ref_count = 1u; + } + + template + Ref::Ref(const Ref & orig) + { + clone_from(orig); + } + + template + Ref & Ref::operator=(const Ref & orig) + { + destroy(); + clone_from(orig); + return *this; + } + + template + Ref & Ref::operator=(T * ptr) + { + destroy(); + m_ptr = ptr; + m_ref_count = new unsigned int; + *m_ref_count = 1u; + return *this; + } + + template + void Ref::clone_from(const Ref & orig) + { + this->m_ptr = orig.m_ptr; + this->m_ref_count = orig.m_ref_count; + if (m_ref_count != NULL) + (*m_ref_count)++; + } + + template + Ref::~Ref() + { + destroy(); + } + + template + void Ref::destroy() + { + if (m_ref_count != NULL) + { + if (*m_ref_count <= 1u) + { + delete m_ptr; + delete m_ref_count; + } + else + { + (*m_ref_count)--; + } + } + } +} + +#endif diff --git a/src/lib/include/jes/Text.h b/src/lib/include/jes/Text.h index 9953603..017942e 100644 --- a/src/lib/include/jes/Text.h +++ b/src/lib/include/jes/Text.h @@ -1,11 +1,14 @@ #ifndef JES_TEXT_H #define JES_TEXT_H +#include "jes/Ref.h" + namespace jes { class Text { }; + typedef Ref TextRef; } #endif