[fpc-pascal] A serious Memleak using delegates/implements (was: Delegate Interface class does not seem to be referenced counted)

Marcos Douglas md at delfire.net
Thu Oct 6 04:01:44 CEST 2016


On Wed, Oct 5, 2016 at 7:07 PM, Tony Whyman
<tony.whyman at mccallumwhyman.com> wrote:
>
>[...]
>
> No, if you explicitly free the provider class there will be no memleaks. My
> point is that having to do this is counter-intuitive and  easy to get wrong
> - or to overlook cases where it is necessary.

That is it, counter-intuitive and  easy to get wrong.

Another thing easily to forget and get memleaks is not get the result
of constructors.
For example. Consider this:

function TFoo.Execute(const Name: string): string;
begin
  Result := TAction.Create(TTask.Create(Name)).Execute.ToString;
end;

- TTask is a class that takes a string in the constructor;
- TTask implements ITask, an interface;
- TAction is a class that receives an ITask interface in the constructor;
- TAction implements IAction, an interface;
- TAction has an Execute method that returns an IResult, an interface;
- IResult has a ToString method that returns the result in string format;

How many memory leaks we have here? 0, 1 or 2?
The answer is 1.

So, we need to declare an variable:

function TFoo.Execute(const Name: string): string;
var
  A: IAction;
begin
  A := TAction.Create(TTask.Create(Name));
  Result := A.Execute.ToString;
end;

Verbose and unnecessary, in my opinion.
Sometimes I forget to declare a variable, sometimes not... this is unproductive!

So, I created my own "design pattern" that I called: New Method.

The refactored code is:

function TFoo.Execute(const Name: string): string;
begin
  Result := TAction.New(TTask.New(Name)).Execute.ToString;
end;

I explained here
http://objectpascalprogramming.com/posts/interfaces-e-o-metodo-estatico-new/
but you need to translate.

>> I understood you but I can't help, because I don't know how the
>> compiler works to do this 'kind of magic' — I think only Object Pascal
>> has delegation in that way, right?
>
> Here I was suggesting a compiler change (bug fix?)

+1

>> Delegates is a powerful feature. I can write less and compose complexy
>> objects using delegation. Really cool.
>>
>> We need to compare with Delphi?
>> I don't have it, but I guess this problem there isn't there.
>
> I never used delegated interfaces in Delphi. In FPC I try to avoid them
> given the problems you get. On the other hand, reference counted com
> interfaces are a great feature and it's a pity delegated interfaces are so
> awkward.

I agree.

Best regards,
Marcos Douglas



More information about the fpc-pascal mailing list