]> git.mxchange.org Git - simgear.git/blob - simgear/structure/ssgSharedPtr.hxx
Mathias Fröhlich:
[simgear.git] / simgear / structure / ssgSharedPtr.hxx
1 /* -*-c++-*-
2  *
3  * Copyright (C) 2005-2006 Mathias Froehlich 
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License as
7  * published by the Free Software Foundation; either version 2 of the
8  * License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  *
19  */
20
21 #ifndef ssgSharedPtr_HXX
22 #define ssgSharedPtr_HXX
23
24 /// This class is a pointer proxy doing reference counting on the object
25 /// it is pointing to.
26 /// It is very similar to the SGSharedPtr class but is made to work together
27 /// with reference counting of plib's ssg reference counters
28 /// For notes on usage see SGSharedPtr.
29
30 template<typename T>
31 class ssgSharedPtr {
32 public:
33   ssgSharedPtr(void) : _ptr(0)
34   {}
35   ssgSharedPtr(T* ptr) : _ptr(ptr)
36   { get(_ptr); }
37   ssgSharedPtr(const ssgSharedPtr& p) : _ptr(p.ptr())
38   { get(_ptr); }
39   template<typename U>
40   ssgSharedPtr(const ssgSharedPtr<U>& p) : _ptr(p.ptr())
41   { get(_ptr); }
42   ~ssgSharedPtr(void)
43   { put(); }
44   
45   ssgSharedPtr& operator=(const ssgSharedPtr& p)
46   { assign(p.ptr()); return *this; }
47   template<typename U>
48   ssgSharedPtr& operator=(const ssgSharedPtr<U>& p)
49   { assign(p.ptr()); return *this; }
50   template<typename U>
51   ssgSharedPtr& operator=(U* p)
52   { assign(p); return *this; }
53
54   T* operator->(void) const
55   { return _ptr; }
56   T& operator*(void) const
57   { return *_ptr; }
58   operator T*(void) const
59   { return _ptr; }
60   T* ptr(void) const
61   { return _ptr; }
62
63   bool isShared(void) const
64   { if (_ptr) return 1 < _ptr->getRef(); else return false; }
65   unsigned getNumRefs(void) const
66   { if (_ptr) return _ptr->getRef(); else return 0; }
67
68   bool valid(void) const
69   { return _ptr; }
70
71 private:
72   void assign(T* p)
73   { get(p); put(); _ptr = p; }
74
75   static void get(T* p)
76   { if (p) p->ref(); }
77   void put(void)
78   {
79     if (!_ptr)
80       return;
81
82     assert(0 < _ptr->getRef());
83     _ptr->deRef();
84     if (_ptr->getRef() == 0) {
85       delete _ptr;
86       _ptr = 0;
87     }
88   }
89   
90   // The reference itself.
91   T* _ptr;
92 };
93
94 #endif