Skip to content

Instantly share code, notes, and snippets.

@omonien
Last active January 23, 2022 11:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save omonien/1c95589bc7f3cca325615c7aad3334b0 to your computer and use it in GitHub Desktop.
Save omonien/1c95589bc7f3cca325615c7aad3334b0 to your computer and use it in GitHub Desktop.
Simple Interface demo.
program Interfaces;
{$APPTYPE CONSOLE}
{$R *.res}
uses
LeakCheck,
System.Classes, System.SysUtils;
type
IFoo = interface(IInterface)
['{EB3BBAA4-6176-48E1-9419-2D6B2B5C6B67}']
procedure Something;
end;
TFoo = class(TInterfacedObject, IFoo)
public
procedure Something;
end;
procedure DoSomething;
begin
//Create an instance of TFoo
var LFoo: IFoo := TFoo.Create;
//Do something with that instance
LFoo.Something;
//No need to cleanup. LFoo goes out of scope, which will trigger TFoo's destructor.
end;
{ TFoo }
procedure TFoo.Something;
begin
Writeln('Something');
end;
begin
ReportMemoryLeaksOnShutdown := true;
try
//Do esomething that creates a couple of TFoo instances
DoSomething;
DoSomething;
// All instances of TFoo are gone here, as they are no longer in use here.
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
Readln;
end.
@omonien
Copy link
Author

omonien commented Jan 23, 2022

Two notes:

  1. When using inline variables, as I do in the example, make sure that you explicitly type them as Interface. By default, the automatically inferred type will be the corresponding class type.
  2. Under certain conditions, the built-in memory manager (which is a FastMM fork), does not reliably detect memory leaks. LeakCheck is cross-platform and seems to be more reliable in corner cases. This sample, in D11.0.2, would not detect a leak with LFoo typed as TFoo, if using the built-in MM.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment