Delphi interface not reference counted

Viewed 678

Reading the Expert Delphi book I have found something that I cannot understand. The author has created an unit with this code:

 IToDoData = interface //CRUD
    function ToDoCreate(aValue: TToDo): integer;
    function ToDoRead(id: integer; out aValue: TToDo): boolean;
    function ToDoUpdate(aValue: TToDo): boolean;
    function ToDoDelete(id: integer): boolean;
    procedure ToDoList(aList: TToDos);
  end;

Then he decided to use a DataModule and implement the above interface in this way:

type
  TDMToDo = class(TDataModule, IToDoData)
    // ... other code ...
  public
    // IToDoData
    function ToDoCreate(aValue: TToDo): integer;
    function ToDoRead(id: integer; out aValue: TToDo): boolean;
    function ToDoUpdate(aValue: TToDo): boolean;
    function ToDoDelete(id: integer): boolean;
    procedure ToDoList(aList: TToDos);
  end;

So far so good but note that he didn't put TInterfacedObject so here we haven't methods like AddRef and so on. My guess is that the above code is fine but it has to be included inside the try ... finally block.

In the main form (the data module unit is the uses clauses of course) there is a function like this:

function TFormToDo.GetToDoData: IToDoData;
begin
  if DMToDo = nil then
    DMToDo := TDMToDo.Create(Application);
  Result := DMToDo;
end;

The code above allows to write code like this:

begin
  GetToDoData.ToDoList(FToDos);

  ListView1.BeginUpdate;
  try
    //populate the list
  finally
    ListView1.EndUpdate;
  end;
end;

Doesn't this produce a memory leak? At least on windows. I am new to delphi so I might fail but I have read online that Android and IOs has ARC so no need to worry about try finally.

Windows does NOT have ARC so I have to use the try .. finally unless there is an implementation like TInterfacedObject (here there isn't). So is that a mistake?


The app is about a ToDo app in which you write/read/save your notes. The data module has FireDAC access components and the interface methods are used to access the db. This is to keep a separation between UI and db stuff.

1 Answers
Related