00001 /* 00002 * This file is part of FREESECS. 00003 * 00004 * FREESECS is free software: you can redistribute it and/or modify 00005 * it under the terms of the GNU General Public License as published by 00006 * the Free Software Foundation, either version 3 of the License, or 00007 * (at your option) any later version. 00008 * 00009 * FREESECS is distributed in the hope that it will be useful, 00010 * but WITHOUT ANY WARRANTY; without even the implied warranty of 00011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 00012 * GNU General Public License for more details. 00013 * 00014 * You should have received a copy of the GNU General Public License 00015 * along with FREESECS, see COPYING. 00016 * If not, see <http://www.gnu.org/licenses/>. 00017 */ 00018 #ifndef _SHARED_PTR_H 00019 #define _SHARED_PTR_H 00020 00021 namespace freesecs 00022 { 00027 template <class T> 00028 class shared_ptr_t 00029 { 00030 private: 00031 T* ptr; 00032 size_t* count; 00033 00034 static size_t* nil() { static size_t nil_counter(1); return &nil_counter; } 00035 00036 void decref() { if (--(*count) == 0) { delete ptr; delete count; }} 00037 void incref() { ++(*count); } 00038 00039 public: 00040 00041 shared_ptr_t() : ptr(0), count(nil()) { incref(); } 00042 ~shared_ptr_t() { decref(); } 00043 00044 shared_ptr_t(const shared_ptr_t<T>& o) : ptr(o.ptr), count(o.count) { incref(); } 00045 shared_ptr_t(T* p) : ptr(p), count(new size_t(1)) {} 00046 00047 shared_ptr_t<T>& operator=(const shared_ptr_t<T>& o) 00048 { 00049 if (ptr == o.ptr) return *this; 00050 decref(); 00051 ptr = o.ptr; 00052 count = o.count; 00053 incref(); 00054 return *this; 00055 } 00056 00057 T* get() { return ptr; } 00058 T* operator->() { return ptr; } 00059 T& operator*() { return *ptr; } 00060 00061 const T* get() const { return ptr; } 00062 const T* operator->() const { return ptr; } 00063 const T& operator*() const { return *ptr; } 00064 00065 bool operator==(const shared_ptr_t<T>& o) const { return ptr == o.ptr; } 00066 bool operator!=(const shared_ptr_t<T>& o) const { return ptr != o.ptr; } 00067 bool operator<(const shared_ptr_t<T>& o) const { return ptr < o.ptr; } 00068 00069 size_t refcount() const { return *count; } 00070 00071 typedef T value_type; 00072 }; 00073 }//namespace 00074 #endif //_SHARED_PTR_H