view anagram/support/pointer.h @ 19:db7ff952e01e

both mansupps seem to be html
author David A. Holland
date Tue, 31 May 2022 02:06:45 -0400
parents 13d2b8934445
children
line wrap: on
line source

/*
 * 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 */