說說Delphi 10.4的對象釋放


隨着Delphi 10.4去掉了ARC,統一移動平台與桌面平台的內存管理,那對於釋放對象,有什么變化呢?

先看看10.4的代碼:

procedure TObject.Free;
begin
// under ARC, this method isn't actually called since the compiler translates
// the call to be a mere nil assignment to the instance variable, which then calls _InstClear
{$IFNDEF AUTOREFCOUNT}
  if Self <> nil then
    Destroy;
{$ENDIF}
end;

procedure TObject.DisposeOf;
type
  TDestructorProc = procedure (Instance: Pointer; OuterMost: ShortInt);
begin
{$IFDEF AUTOREFCOUNT}
  if Self <> nil then
  begin
    Self.__ObjAddRef; // Ensure the instance remains alive throughout the disposal process
    try
      if __SetDisposed(Self) then
      begin
        _BeforeDestruction(Self, 1);
        TDestructorProc(PPointer(PByte(PPointer(Self)^) + vmtDestroy)^)(Self, 0);
      end;
    finally
      Self.__ObjRelease; // This will deallocate the instance if the above process cleared all other references.
    end;
  end;
{$ELSE}
  Free;
{$ENDIF}
end;

可以清楚的看到,在DisposeOf中,如果沒有定義AUTOREFCOUNT編譯變量,則直接調用Free方法。由於去掉ARC,AUTOREFCOUNT不再定義,所以調用DisposeOf,就是調用Free。現在可以忘記DisposeOf了,所有平台釋放對象,就用Free。

接下來,再看看FreeAndNil方法:

procedure FreeAndNil(const [ref] Obj: TObject);
{$IF not Defined(AUTOREFCOUNT)}
var
  Temp: TObject;
begin
  Temp := Obj;
  TObject(Pointer(@Obj)^) := nil;
  Temp.Free;
end;
{$ELSE}
begin
  Obj := nil;
end;
{$ENDIF}

這個方法,同樣使用了AUTOREFCOUNT編譯變量。

為了驗證移動平台下,是否定義了AUTOREFCOUNT,筆者做了個測試代碼:

procedure TForm1.FormCreate(Sender: TObject);
begin
{$IFDEF AUTOREFCOUNT}
   Text1.Text:='AUTOREFCOUNT';
{$ELSE}
   Text1.Text:='Not Defined AUTOREFCOUNT';
{$ENDIF}
end;

事實證明,在android運行時,顯示Not Defined AUTOREFCOUNT。沒有定義AUTOREFCOUNT,你可按這個去讀上面的代碼了!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM