Merged changes from branches/supertux-milestone2-grumbel/ to trunk/supertux/
[supertux.git] / src / util / ref.hpp
1 //  SuperTux
2 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
3 //
4 //  This program is free software: you can redistribute it and/or modify
5 //  it under the terms of the GNU General Public License as published by
6 //  the Free Software Foundation, either version 3 of the License, or
7 //  (at your option) any later version.
8 //
9 //  This program is distributed in the hope that it will be useful,
10 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
11 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 //  GNU General Public License for more details.
13 //
14 //  You should have received a copy of the GNU General Public License
15 //  along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
17 #ifndef HEADER_SUPERTUX_UTIL_REF_HPP
18 #define HEADER_SUPERTUX_UTIL_REF_HPP
19
20 /** This class behaves like a pointer to a refcounted object, but increments the
21  * reference count when new objects are assigned and decrements the refcounter
22  * when its lifetime has expired. (similar to std::auto_ptr)
23  */
24 template<typename T>
25 class Ref
26 {
27 public:
28   Ref(T* object = 0)
29     : object(object)
30   {
31     if(object)
32       object->ref();
33   }
34   Ref(const Ref<T>& other)
35     : object(other.object)
36   {
37     if(object)
38       object->ref();
39   }
40   ~Ref()
41   {
42     if(object)
43       object->unref();
44   }
45   
46   Ref<T>& operator= (const Ref<T>& other)
47   {
48     *this = other.get();
49     return *this;
50   }
51
52   Ref<T>& operator= (T* object)
53   {
54     if(object)
55       object->ref();
56     if(this->object)
57       this->object->unref();
58     this->object = object;
59
60     return *this;
61   }
62
63   T* operator ->() const
64   {
65     return object;
66   }
67
68   T& operator* () const
69   {
70     return *object;
71   }
72
73   operator const T* () const
74   {
75     return object;
76   }
77
78   T* get() const
79   {
80     return object;
81   }
82
83 private:
84   T* object;
85 };
86
87 #endif
88
89 /* EOF */