[fpc-pascal] Out of scope method?

Marcos Douglas B. Santos md at delfire.net
Thu Apr 6 15:54:10 CEST 2017


On Thu, Apr 6, 2017 at 10:41 AM, Ryan Joseph <ryan at thealchemistguild.com> wrote:
>
>> On Apr 6, 2017, at 8:13 PM, Marcos Douglas B. Santos <md at delfire.net> wrote:
>>
>> I can guarantee that reference counting is not a bad idea.
>> I have been using this for years and in my own code I do not use Free
>> method anymore (only if I need to use some classes of RTL or some 3rd
>> libs/frameworks), internally, on private methods.
>>
>> But you need to code using another approach, another mindset...
>
> What method are you using? I found some examples for Delphi that didn’t seem to work in Free Pascal.
>
> Currently I’ve implemented something similar to that found in the Objective-C frameworks called autoreleasing which adds the object to a pool which is drained and the objects freed at the end of every event cycle (after it’s left scope for certain). That works pretty well actually (anyone else ever do this in Pascal?) but the same thing could be achieved with less overhead if the compiler told me when an instance left scope. Specially in a few cases you could load up the pool too large and cause performance problems so I need to be careful of that.
>

First of all, you should use interfaces variables, always.
Sometimes you will have memory leaks and will think that ref counting not work.
See an example:

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

Even if TAction implement an IAction interface, you will have a memory
leak here because you don't have an variable (a: IAction) receiving an
instance of TAction.

I am talking about this:

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

Pretty clear, right?

Because this "problem" I have a "pattern" that I called "New Method".

You can see how it works in my article:
(you need to translate from Portuguese)
http://objectpascalprogramming.com/posts/interfaces-e-o-metodo-estatico-new/

Best regards,
Marcos Douglas



More information about the fpc-pascal mailing list