melee / ranged effects
[gemrb.git] / gemrb / core / Holder.h
blob170a4c87e4b60bdd8ce8f89372d7ef5426d334f1
1 /* GemRB - Infinity Engine Emulator
2 * Copyright (C) 2003 The GemRB Project
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version 2
7 * of the License, or (at your option) any later version.
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.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 #ifndef HOLDER_H
22 #define HOLDER_H
24 #include <cassert>
25 #include <cstddef>
27 template <class T>
28 class Held {
29 public:
30 Held() : RefCount(0) {}
31 void acquire() { ++RefCount; }
32 void release() { assert(RefCount && "Broken Held usage.");
33 if (!--RefCount) delete static_cast<T*>(this); }
34 size_t GetRefCount() { return RefCount; }
35 private:
36 size_t RefCount;
39 /**
40 * @class Holder
41 * Intrusive smart pointer.
43 * The class T must have member function acquire and release, such that
44 * acquire increases the refcount, and release decreses the refcount and
45 * frees the object if needed.
47 * Derived class of Holder shouldn't add member variables. That way,
48 * they can freely converted to Holder without slicing.
51 template <class T>
52 class Holder {
53 public:
54 Holder(T* ptr = NULL)
55 : ptr(ptr)
57 if (ptr)
58 ptr->acquire();
60 ~Holder()
62 if (ptr)
63 ptr->release();
65 Holder(const Holder& rhs)
66 : ptr(rhs.ptr)
68 if (ptr)
69 ptr->acquire();
71 Holder& operator=(const Holder& rhs)
73 if (rhs.ptr)
74 rhs.ptr->acquire();
75 if (ptr)
76 ptr->release();
77 ptr = rhs.ptr;
78 return *this;
80 T& operator*() const { return *ptr; }
81 T* operator->() const { return ptr; }
82 bool operator!() const { return !ptr; }
83 #include "operatorbool.h"
84 OPERATOR_BOOL(Holder<T>,T,ptr)
85 T* get() const { return ptr; }
86 void release() {
87 if (ptr)
88 ptr->release();
89 ptr = NULL;
91 protected:
92 T *ptr;
95 #endif