Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

does the observer implementation here has memory leak?

maybe i dont know delphi all that well, however i wish to ask you:

at this site : http://blogs.teamb.com/joannacarter/2004/06/30/690 i found an implemetation of observer pattern based on iterface.

when doing attach , there is a call to this:

procedure TSubject.Attach(Observer: IObserver);
begin
    if fObservers = nil then
      fObservers := TInterfaceList.Create;
    fObservers.Add(AObserver);
    Notify;
end;

and in the detach it has the code

procedure TSubject.Detach(Observer: IObserver);
begin
   if fObservers <> nil then
    begin
      fObservers.Remove(AObserver);
      if fObservers.Count = 0 then
        fObservers := nil;
    end;
end;

should it be :

procedure TSubject.Detach(Observer: IObserver);
begin
   if fObservers <> nil then
    begin
      fObservers.Remove(AObserver);
      if fObservers.Count = 0 then begin
        fObservers.Free; 
        fObservers := nil;
      end;
    end;
end;
like image 757
none Avatar asked Aug 12 '26 05:08

none


2 Answers

No, it shouldn't, because as Bharat said, IInterface will take care of that. Note that fObservers is declared as IInterfaceList in the example you're reffering to. It's an interface. Interface variables in Delphi are akin to smart pointers in C++, they call _Addref and _Release on assignments automatically.

If fObservers was declared as TInterfaceList, on the other hand, then it would be an object, and objects don't do anything special on assignment, so it would have been correct to call Free.

like image 147
himself Avatar answered Aug 14 '26 15:08

himself


There is no need to add fObservers.Free; statement. IInterface will take care of adding and releasing the fObservers .

Delphi uses _AddRef and _Release to manage the lifetime of interfaced objects.

When you assign an interface reference to an interface variable, Delphi automatically calls _AddRef.

When the variable goes out of scope, Delphi automatically calls _Release.

For more info go through this link.

like image 30
Bharat Avatar answered Aug 14 '26 15:08

Bharat