Geant4 Cross Reference |
1 // Copyright (C) 2010, Guy Barrand. All rights reserved. 2 // See the file tools.license for terms. 3 4 #ifndef tools_handle 5 #define tools_handle 6 7 #ifdef TOOLS_MEM 8 #include "mem" 9 #endif 10 11 #include <string> 12 13 namespace tools { 14 15 class base_handle { 16 static const std::string& s_class() { 17 static const std::string s_v("tools::handle"); 18 return s_v; 19 } 20 public: 21 virtual void* object() const = 0; 22 virtual base_handle* copy() = 0; //can't be const. 23 virtual void disown() = 0; 24 public: 25 base_handle(){ 26 #ifdef TOOLS_MEM 27 mem::increment(s_class().c_str()); 28 #endif 29 } 30 base_handle(const std::string& a_class):m_class(a_class){ 31 #ifdef TOOLS_MEM 32 mem::increment(s_class().c_str()); 33 #endif 34 } 35 virtual ~base_handle(){ 36 #ifdef TOOLS_MEM 37 mem::decrement(s_class().c_str()); 38 #endif 39 } 40 protected: 41 base_handle(base_handle& a_from):m_class(a_from.m_class){ 42 #ifdef TOOLS_MEM 43 mem::increment(s_class().c_str()); 44 #endif 45 } 46 private: 47 base_handle& operator=(base_handle& a_from){ 48 m_class = a_from.m_class; 49 return *this; 50 } 51 public: 52 const std::string& object_class() const {return m_class;} 53 private: 54 std::string m_class; 55 }; 56 57 template <class T> 58 class handle : public base_handle { 59 typedef base_handle parent; 60 public: 61 virtual void* object() const {return m_obj;} 62 virtual base_handle* copy() {return new handle<T>(*this);} 63 virtual void disown() {m_owner = false;} 64 public: 65 handle(T* a_obj,bool a_owner = true):parent(),m_obj(a_obj),m_owner(a_owner){} 66 handle(const std::string& a_class,T* a_obj,bool a_owner = true):parent(a_class),m_obj(a_obj),m_owner(a_owner){} 67 virtual ~handle(){if(m_owner) delete m_obj;} 68 private: 69 handle(handle& a_from):parent(a_from){ 70 m_obj = a_from.m_obj; 71 if(a_from.m_owner) { 72 // this take ownership. 73 m_owner = true; 74 a_from.m_owner = false; 75 } else { 76 m_owner = false; 77 } 78 //a_from.m_obj = 0; //we do not remove the obj ref in a_from. 79 } 80 private: 81 // in principle the below are not used. 82 //handle(const handle& a_from){} 83 //handle& operator=(const handle&){return *this;} 84 handle& operator=(handle&){return *this;} 85 protected: 86 T* m_obj; 87 bool m_owner; 88 }; 89 90 } 91 92 #endif