inlib  1.2.0
/Users/barrand/private/dev/softinex/old/inexlib-1.2/inlib/inlib/handle
Go to the documentation of this file.
00001 // Copyright (C) 2010, Guy Barrand. All rights reserved.
00002 // See the file inlib.license for terms.
00003 
00004 #ifndef inlib_handle
00005 #define inlib_handle
00006 
00007 #ifdef INLIB_MEM
00008 #include "mem"
00009 #endif
00010 
00011 #include <string>
00012 
00013 namespace inlib {
00014 
00015 class base_handle {
00016   static const std::string& s_class() {
00017     static const std::string s_v("inlib::handle");
00018     return s_v;
00019   }
00020 public:  
00021   virtual void* object() const = 0;
00022   virtual base_handle* copy() = 0; //can't be const.
00023   virtual void disown() = 0;
00024 public:  
00025   base_handle(){
00026 #ifdef INLIB_MEM
00027     mem::increment(s_class().c_str());
00028 #endif
00029   }
00030   virtual ~base_handle(){
00031 #ifdef INLIB_MEM
00032     mem::decrement(s_class().c_str());
00033 #endif
00034   }
00035 protected:
00036   base_handle(base_handle&){
00037 #ifdef INLIB_MEM
00038     mem::increment(s_class().c_str());
00039 #endif
00040   }
00041 private:
00042   //base_handle(const base_handle&){}
00043   //base_handle& operator=(const base_handle&){return *this;}
00044   base_handle& operator=(base_handle&){return *this;}
00045 };
00046 
00047 template <class T>
00048 class handle : public base_handle {
00049 public:  
00050   virtual void* object() const {return m_obj;}
00051   virtual base_handle* copy() {return new handle<T>(*this);}
00052   virtual void disown() {m_owner = false;}
00053 public:  
00054   handle(T* a_obj,bool a_owner = true)
00055   : base_handle()
00056   ,m_obj(a_obj),m_owner(a_owner){}
00057   virtual ~handle(){if(m_owner) delete m_obj;}
00058 private:
00059   handle(handle& a_from):base_handle(a_from){
00060     m_obj = a_from.m_obj;
00061     if(a_from.m_owner) {
00062       // this take ownership.
00063       m_owner = true;
00064       a_from.m_owner = false;
00065     } else {
00066       m_owner = false;
00067     }
00068     //a_from.m_obj = 0; //we do not remove the obj ref in a_from.    
00069   }
00070 private:
00071   // in principle the below are not used.
00072   //handle(const handle& a_from){}
00073   //handle& operator=(const handle&){return *this;}
00074   handle& operator=(handle&){return *this;}
00075 protected:
00076   T* m_obj;
00077   bool m_owner;
00078 };
00079 
00080 }
00081 
00082 #endif
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Defines