Mercurial > ~dholland > hg > ag > index.cgi
diff 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 |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/anagram/support/pointer.h Sat Dec 22 17:52:45 2007 -0500 @@ -0,0 +1,75 @@ +/* + * AnaGram, A System for Syntax Directed Programming + * Copyright 1997-2002 Parsifal Software. All Rights Reserved. + * See the file COPYING for license and usage terms. + * + * pointer.h + */ + +#ifndef POINTER_H +#define POINTER_H + +template <class T> +class Pointer { +private: + int *useCount; + T *item; + +public: + Pointer(T *i) : useCount(new int), item(i) { useCount = 1; } + Pointer(const Pointer<T> &x) : useCount(x.useCount), item(x.item) { + (*useCount)++; + } + Pointer<T> &operator = (const Pointer<T> &x) { + if (--(*useCount) == 0) { + // XXX doesn't this leak the usecount memory? + delete item; + } + useCount = x.useCount; + item = x.item; + (*useCount)++; + } + ~Pointer() { + if (--(*useCount) == 0) { + delete item; + delete useCount; + } + } + T *operator ->() { return item; } +}; + +template <class T> +class ArrayPointer { +private: + int *useCount; + T *array; + +public: + ArrayPointer(T *i) : useCount(new int), array(i) { *useCount = 1; } + ArrayPointer(const ArrayPointer<T> &x) : useCount(x.useCount),array(x.array){ + (*useCount)++; + } + ArrayPointer<T> &operator = (const ArrayPointer<T> &x) { + if (--(*useCount) == 0) { + // XXX doesn't this leak the usecount memory? + delete [] array; + } + useCount = x.useCount; + array = x.array; + (*useCount)++; + return *this; + } + ~ArrayPointer() { + if (--(*useCount) == 0) { + delete [] array; + delete useCount; + } + } + const T &operator [] (const int x) const { return array[x]; } + T &operator [] (const int x) { return array[x]; } + operator const T *() const { return array; } + operator T *() { return array; } +}; + + +#endif /* POINTER_H */