New grow and skid sounds from remaxim
[supertux.git] / src / ref.hpp
1 //  $Id$
2 //
3 //  SuperTux
4 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
5 //
6 //  This program is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU General Public License
8 //  as published by the Free Software Foundation; either version 2
9 //  of the License, or (at your option) any later version.
10 //
11 //  This program is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 //  GNU General Public License for more details.
15 //
16 //  You should have received a copy of the GNU General Public License
17 //  along with this program; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
19 //  02111-1307, USA.
20 #ifndef __REF_HPP__
21 #define __REF_HPP__
22
23 /** This class behaves like a pointer to a refcounted object, but increments the
24  * reference count when new objects are assigned and decrements the refcounter
25  * when its lifetime has expired. (similar to std::auto_ptr)
26  */
27 template<typename T>
28 class Ref
29 {
30 public:
31   Ref(T* object = 0)
32     : object(object)
33   {
34     if(object)
35       object->ref();
36   }
37   Ref(const Ref<T>& other)
38     : object(other.object)
39   {
40     if(object)
41       object->ref();
42   }
43   ~Ref()
44   {
45     if(object)
46       object->unref();
47   }
48
49   void operator= (const Ref<T>& other)
50   {
51     *this = other.get();
52   }
53
54   void operator= (T* object)
55   {
56     if(object)
57       object->ref();
58     if(this->object)
59       this->object->unref();
60     this->object = object;
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