Back to index

lightning-sunbird  0.9+nobinonly
icptrholder.h
Go to the documentation of this file.
00001 /* -*- Mode: C++ -*- */
00002 
00028 #ifndef __ICPTRHOLDER_H__
00029 #define __ICPTRHOLDER_H__
00030 
00031 template<class T> class ICPointerHolder {
00032 public:
00033     ICPointerHolder() { ptr = NULL; }
00034     ICPointerHolder(T* p) { ptr = p; }
00035 
00036     // copy constructor to support assignment
00037     ICPointerHolder(const ICPointerHolder& ip) {
00038         ptr = ip.ptr;
00039 
00040         // We need to transfer ownership of ptr to this object by setting
00041         // ip's ptr to null. Otherwise, ptr will de deleted twice.
00042         // const ugliness requires us to do the const_cast.
00043         ICPointerHolder *ipp = const_cast<ICPointerHolder*>(&ip);
00044         ipp->ptr = NULL;
00045     };
00046 
00047    ~ICPointerHolder() {
00048         release();
00049     }
00050 
00051     ICPointerHolder& operator=(T* p) {
00052         this->release();
00053         ptr = p;
00054         return *this;
00055     }
00056 
00057     ICPointerHolder& operator=(ICPointerHolder& p) {
00058         this->release();
00059         ptr = p.ptr;            // this transfer ownership of the pointer
00060         p.ptr = NULL;           // set it to null so the pointer won't get delete twice.
00061         return *this;
00062     }
00063 
00064     int operator!=(T* p) {return (ptr != p);}
00065     int operator==(T* p) {return (ptr == p);}
00066 
00067     operator T*() const {
00068         return ptr;
00069     }
00070 
00071     T* operator->() const {
00072         assert(ptr);
00073         return ptr;
00074     }
00075 
00076     T& operator*() {
00077         assert(ptr);
00078         return *ptr;
00079     }
00080 
00081 private:
00082     void  release() {
00083         if (ptr != NULL) {
00084             ptr->detach();
00085             delete ptr;
00086             ptr = NULL;
00087         }
00088     }
00089 
00090     T*    ptr;
00091 };
00092 
00093 #endif