[fpc-pascal] Delegate Interface class does not seem to be referenced counted

Tony Whyman tony.whyman at mccallumwhyman.com
Wed Aug 10 17:47:28 CEST 2016


Graeme,

You are explicitly freeing MyClass. My point is that with reference 
counted interfaces and in the example I posted, you shouldn't have to 
explicitly free the delegated interface. It should be freed 
automatically as soon as it goes out of scope.

Tony Whyman

MWA

On 10/08/16 16:43, Graeme Geldenhuys wrote:
> On 2016-08-10 13:42, Tony Whyman wrote:
>> In the example, TMyClass is the interface class doing the delegation and
>> while TDelegateClass is being destroyed when it goes out of scope,
>> TMyClass is not.
> Maybe I'm missing something, but here is a quick example I put together.
> Testing with FPC 2.6.4 under FreeBSD and classes are created and freed
> as they are supposed to.
>
> Here is the console output:
>
> $ ./test2
> Creating TMyClass
> Creating TMyInterface
> TMyInterface.P1
> TMyInterface.P2
> Destroying TMyClass
> Destroying TMyInterface
>
> And the code for the test project.
>
> ===================[ test2.pas ]=======================
> program test2;
>
> {$mode objfpc}{$H+}
>
> { Delegating to an interface-type property }
>
> type
>    IMyInterface = interface
>      procedure P1;
>      procedure P2;
>    end;
>
>    TMyInterface = class(TInterfacedObject, IMyInterface)
>    private
>       procedure P1;
>       procedure P2;
>    public
>      constructor Create;
>      destructor Destroy; override;
>    end;
>
>    TMyClass = class(TObject, IMyInterface)
>      FMyInterface: IMyInterface;
>      property MyInterface: IMyInterface read FMyInterface implements
> IMyInterface;
>    public
>      constructor Create;
>      destructor Destroy; override;
>    end;
>
>
> procedure TMyInterface.P1;
> begin
>    writeln('TMyInterface.P1');
> end;
>
> procedure TMyInterface.P2;
> begin
>    writeln('TMyInterface.P2');
> end;
>
> constructor TMyInterface.Create;
> begin
>    writeln('Creating ',ClassName);
> end;
>
> destructor TMyInterface.Destroy;
> begin
>    writeln('Destroying ',ClassName);
>    inherited Destroy;
> end;
>
>
>
> var
>    MyClass: TMyClass;
>    MyInterface: IMyInterface;
>
> { TMyClass }
>
> constructor TMyClass.Create;
> begin
>    writeln('Creating ',ClassName);
> end;
>
> destructor TMyClass.Destroy;
> begin
>    writeln('Destroying ',ClassName);
>    inherited Destroy;
> end;
>
> begin
>    MyClass := TMyClass.Create;
>    MyClass.FMyInterface := TMyInterface.Create;  // some object whose
> class implements IMyInterface
>    MyInterface := MyClass;
>    MyInterface.P1;
>    MyInterface.P2;
>    MyClass.Free;
> end.
>
> ========================[ end ]========================
>
> Regards,
>    Graeme
>




More information about the fpc-pascal mailing list