view tests/agcl/ffcalc/number.h @ 20:bb115deb6fb2

Improve agfiles rule. (1) It didn't depend on $(AGCL) and it absolutely should have. (2) allow AGFORCE=1 to make it rebuild whether or not it looks out of date. (3) Document this.
author David A. Holland
date Mon, 13 Jun 2022 00:02:15 -0400
parents 13d2b8934445
children
line wrap: on
line source

#ifndef NUMBER_H
#define NUMBER_H

#include <stdio.h>
#include <assert.h>

class Number {
	double value;
	int valid;
	int *useCount;
	int serialNumber;
	static int nCreated;
	static char buf[];
	void logCreation() {*useCount = 1; printf("Create: %d\n", serialNumber); fflush(stdout);
	}
public:
	Number() : valid(0), useCount(new int), serialNumber(nCreated++) {logCreation();}
	Number(double d) : value(d), valid(1), useCount(new int), serialNumber(nCreated++) {logCreation();}
	Number(const Number &n)
	  : value(n.value),
		  valid(n.valid),
			useCount(n.useCount),
			serialNumber(n.serialNumber)
{
  (*useCount)++;
	printf("Copy constructor: %s\n", n.asString());
	printf("Copy constructor: %s\n", asString());
	 fflush(stdout);
}
	~Number() {
		assert(*useCount > 0);
		if (--(*useCount) == 0) printf("Delete %d\n", serialNumber);
		else printf("Destructor: %s\n", asString());
		fflush(stdout);
	}
	char *asString() const {
		char *vs = valid ? "valid" : "invalid";
		sprintf(buf, "%X: sn%d(%s) = %G, *%X = %d", this, serialNumber, vs, value, useCount, *useCount);
		return buf;
	}
	Number &operator = (const Number &n)  {
		assert(*useCount > 0);
		if (--(*useCount) == 0) printf("Delete %d\n", serialNumber);
		fflush(stdout);
		useCount = n.useCount;
		value = n.value;
		valid = n.valid;
		serialNumber = n.serialNumber;
		(*useCount)++;
		return *this;
	}
	Number &operator += (const Number &n) {valid |= n.valid; value += n.value; return *this;}
	Number &operator -= (const Number &n) {valid |= n.valid; value -= n.value; return *this;}
	Number &operator *= (const Number &n) {valid |= n.valid; value *= n.value; return *this;}
	Number &operator /= (const Number &n) {valid |= n.valid; if(valid) value /= n.value; return *this;}
	Number &operator -() {value = -value; return *this;}
	operator char * () {
		if (valid) {
			sprintf(buf, "%G", value);
			printf("operator char * = %g\n", value);
			return buf;
		}
		else return "Invalid";
	}
};

#endif