view anagram/support/pointer.h @ 6:607e3be6bad8

Adjust to the moving target called the C++ standard. Apparently nowadays it's not allowed to define an explicit copy constructor but not an assignment operator. Consequently, defining the explicit copy constructor in terms of the implicit/automatic assignment operator for general convenience no longer works. Add assignment operators. Caution: not tested with the IBM compiler, but there's no particular reason it shouldn't work.
author David A. Holland
date Mon, 30 May 2022 23:46:22 -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 */