ee020e0eb8783f3af6579f8960b4ae1707b9b18d
[libs/core.git] / source / core / refptr.h
1 /* $Id$
2
3 This file is part of libmspcore
4 Copyright © 2006-2007 Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
6 */
7 #ifndef MSP_CORE_REFPTR_H_
8 #define MSP_CORE_REFPTR_H_
9
10 namespace Msp {
11
12 template<typename T>
13 class RefPtr
14 {
15 public:
16         RefPtr(): data(0), count(0) { }
17         RefPtr(T *d): data(d), count(0) { if(data) count=new unsigned(1); }
18         RefPtr(const RefPtr &p): data(p.data), count(p.count) { incref(); }
19         ~RefPtr() { decref(); }
20
21         RefPtr &operator=(const RefPtr &p)
22         {
23                 decref();
24                 data=p.data;
25                 count=p.count;
26                 incref();
27                 return *this;
28         }
29
30         T *get() const        { return data; }
31         T &operator*() const  { return *data; }
32         T *operator->() const { return data; }
33         operator bool() const { return data!=0; }
34
35         template<typename U>
36         static RefPtr<T> cast_dynamic(const RefPtr<U> &p)  { return RefPtr<T>(dynamic_cast<T *>(p.get()), p.count); }
37         template<typename U> friend class RefPtr;
38 private:
39         T        *data;
40         unsigned *count;
41
42         RefPtr(T *d, unsigned *c): data(d), count(c) { incref(); }
43
44         void  incref()
45         {
46                 if(!count) return;
47                 ++*count;
48         }
49
50         void  decref()
51         {
52                 if(!count) return;
53                 --*count;
54                 if(!*count)
55                 {
56                         delete data;
57                         delete count;
58                         data=0;
59                         count=0;
60                 }
61         }
62 };
63
64 } // namespace Msp
65
66 #endif