From 147337c53f4427a2fb12f73c536dad27a04c2344 Mon Sep 17 00:00:00 2001 From: Samer Afach Date: Thu, 6 Apr 2017 11:36:17 +0200 Subject: [PATCH] Add SmartPtr.h --- SmartPtr.h | 205 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 205 insertions(+) create mode 100644 SmartPtr.h diff --git a/SmartPtr.h b/SmartPtr.h new file mode 100644 index 0000000..25b0f6c --- /dev/null +++ b/SmartPtr.h @@ -0,0 +1,205 @@ +#ifndef SMARTPTR_H +#define SMARTPTR_H + +#include +#include +#include + +/** + * Simple shared pointer class with NO thread safety (not even the counter is thread-safe) + */ +template +class SmartPtr +{ + //Rule 1: tracker is always NULL when ptr == NULL + //Rule 2: ID is only assigned in constructors + + typedef std::map*> IDMap; + typedef std::pair*> IDPair; + + T* ptr; + IDMap *tracker; //track pointers to same object + unsigned long ID; + static unsigned long __IDCounter; + +public: + typedef T element_type; + SmartPtr(const SmartPtr& other); + SmartPtr& operator=(const SmartPtr& other); + SmartPtr(T* new_ptr = NULL); + T& operator*(); + const T& operator*() const; + ~SmartPtr(); + unsigned long use_count() const; + operator bool(); + T* get(); + const T* const get() const; + T* release(); + void reset(T* new_ptr = NULL); + inline bool isNull(); + template