[fpc-pascal] Re: operator overloading and counting references / creating / destoying anonymous instances

Bernd prof7bit at googlemail.com
Sat Jul 30 23:02:31 CEST 2011


2011/7/30 Florian Klämpfl <florian at freepascal.org>:

> This is exactly what ref. counting solves? Did you read my other mail
> regarding your problem with ref. counting?

Yes, of course Ref counting "solves" it (in the sense that it can all
be made to work as expected and not leak memory) and your suggestion
of checking the reference counter also solves the problem of detecting
when a copy would be needed and when it is safe to recycle the
existing object.

But this does not solve the initial problem that in most cases with
operator overloading I simply do not have any access to the result and
*must* create a new instance and in my  bignum example this is 3 times
slower than intelligently reusing existing objects.

A := B + C

The code in the plus operator cannot access A to change it even if it
were safe to recycle the existing instance. It does not even know
about the A, it has no way of looking "through" the function result to
see what is on the other side and check its ref count, and so it
*always* must create a new A and let the ref counting dispose the old
one.

procedure Add(var A, B, C: TBigNum);

could check the ref count of A and optimize this greatly and simply
recycle the existing instance if it detects that it is the only one.
But a function

function Add(A, B: TBigNum): TBigNum;

does not have any other chance than *always* creating a new instance.
Result is always nil, I cannot look "through" it, its a one-way
street, I cannot make any assumptions what the result is used for and
cannot check it at runtime. If the operator overloading functions
could be defined like this (pseudo code):

operator + (var Result: TBigNum;  A, B: TBigNum);

then maybe but I'm not sure whether it would even be possible to make
the compiler arrange things in such a way that such a thing could be
done.



More information about the fpc-pascal mailing list