00001 /* -*-c++-*- 00002 * 00003 * Copyright (C) 2005-2006 Mathias Froehlich 00004 * 00005 * This program is free software; you can redistribute it and/or 00006 * modify it under the terms of the GNU General Public License as 00007 * published by the Free Software Foundation; either version 2 of the 00008 * License, or (at your option) any later version. 00009 * 00010 * This program is distributed in the hope that it will be useful, but 00011 * WITHOUT ANY WARRANTY; without even the implied warranty of 00012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 00013 * General Public License for more details. 00014 * 00015 * You should have received a copy of the GNU General Public License 00016 * along with this program; if not, write to the Free Software 00017 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 00018 * 00019 */ 00020 00021 #ifndef SGSharedPtr_HXX 00022 #define SGSharedPtr_HXX 00023 00024 #include "SGReferenced.hxx" 00025 00044 00045 template<typename T> 00046 class SGSharedPtr { 00047 public: 00048 SGSharedPtr(void) : _ptr(0) 00049 {} 00050 SGSharedPtr(T* ptr) : _ptr(ptr) 00051 { get(_ptr); } 00052 SGSharedPtr(const SGSharedPtr& p) : _ptr(p.ptr()) 00053 { get(_ptr); } 00054 template<typename U> 00055 SGSharedPtr(const SGSharedPtr<U>& p) : _ptr(p.ptr()) 00056 { get(_ptr); } 00057 ~SGSharedPtr(void) 00058 { put(); } 00059 00060 SGSharedPtr& operator=(const SGSharedPtr& p) 00061 { assign(p.ptr()); return *this; } 00062 template<typename U> 00063 SGSharedPtr& operator=(const SGSharedPtr<U>& p) 00064 { assign(p.ptr()); return *this; } 00065 template<typename U> 00066 SGSharedPtr& operator=(U* p) 00067 { assign(p); return *this; } 00068 00069 T* operator->(void) const 00070 { return _ptr; } 00071 T& operator*(void) const 00072 { return *_ptr; } 00073 operator T*(void) const 00074 { return _ptr; } 00075 T* ptr(void) const 00076 { return _ptr; } 00077 00078 bool isShared(void) const 00079 { return SGReferenced::shared(_ptr); } 00080 unsigned getNumRefs(void) const 00081 { return SGReferenced::count(_ptr); } 00082 00083 bool valid(void) const 00084 { return _ptr; } 00085 00086 private: 00087 void assign(T* p) 00088 { get(p); put(); _ptr = p; } 00089 00090 void get(const T* p) const 00091 { SGReferenced::get(p); } 00092 void put(void) 00093 { if (!SGReferenced::put(_ptr)) { delete _ptr; _ptr = 0; } } 00094 00095 // The reference itself. 00096 T* _ptr; 00097 }; 00098 00099 #endif
1.5.1