comparison anagram/support/pointer.h @ 0:13d2b8934445

Import AnaGram (near-)release tree into Mercurial.
author David A. Holland
date Sat, 22 Dec 2007 17:52:45 -0500
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:13d2b8934445
1 /*
2 * AnaGram, A System for Syntax Directed Programming
3 * Copyright 1997-2002 Parsifal Software. All Rights Reserved.
4 * See the file COPYING for license and usage terms.
5 *
6 * pointer.h
7 */
8
9 #ifndef POINTER_H
10 #define POINTER_H
11
12 template <class T>
13 class Pointer {
14 private:
15 int *useCount;
16 T *item;
17
18 public:
19 Pointer(T *i) : useCount(new int), item(i) { useCount = 1; }
20 Pointer(const Pointer<T> &x) : useCount(x.useCount), item(x.item) {
21 (*useCount)++;
22 }
23 Pointer<T> &operator = (const Pointer<T> &x) {
24 if (--(*useCount) == 0) {
25 // XXX doesn't this leak the usecount memory?
26 delete item;
27 }
28 useCount = x.useCount;
29 item = x.item;
30 (*useCount)++;
31 }
32 ~Pointer() {
33 if (--(*useCount) == 0) {
34 delete item;
35 delete useCount;
36 }
37 }
38 T *operator ->() { return item; }
39 };
40
41 template <class T>
42 class ArrayPointer {
43 private:
44 int *useCount;
45 T *array;
46
47 public:
48 ArrayPointer(T *i) : useCount(new int), array(i) { *useCount = 1; }
49 ArrayPointer(const ArrayPointer<T> &x) : useCount(x.useCount),array(x.array){
50 (*useCount)++;
51 }
52 ArrayPointer<T> &operator = (const ArrayPointer<T> &x) {
53 if (--(*useCount) == 0) {
54 // XXX doesn't this leak the usecount memory?
55 delete [] array;
56 }
57 useCount = x.useCount;
58 array = x.array;
59 (*useCount)++;
60 return *this;
61 }
62 ~ArrayPointer() {
63 if (--(*useCount) == 0) {
64 delete [] array;
65 delete useCount;
66 }
67 }
68 const T &operator [] (const int x) const { return array[x]; }
69 T &operator [] (const int x) { return array[x]; }
70 operator const T *() const { return array; }
71 operator T *() { return array; }
72 };
73
74
75 #endif /* POINTER_H */