Merged changes from branches/supertux-milestone2-grumbel/ to trunk/supertux/
[supertux.git] / src / util / refcounter.hpp
1 //  Windstille - A Jump'n Shoot Game
2 //  Copyright (C) 2005 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_REFCOUNTER_HPP
18 #define HEADER_SUPERTUX_UTIL_REFCOUNTER_HPP
19
20 #include <assert.h>
21
22 /**
23  * A base class that provides reference counting facilities
24  */
25 class RefCounter
26 {
27 public:
28   RefCounter()
29     : refcount(0)
30   { }
31
32   /** increases reference count */
33   void ref()
34   {
35     refcount++;
36   }
37   /** decreases reference count. Destroys the object if the reference count
38    * reaches 0
39    */
40   void unref()
41   {
42     refcount--;
43     if(refcount <= 0) {
44       delete this;
45     }
46   }
47
48 protected:
49   virtual ~RefCounter()
50   {
51     assert(refcount == 0);
52   }
53
54 private:
55   int refcount;
56 };
57
58 #endif
59
60 /* EOF */