回覆列表
  • 1 # Tiekt鐵鐵

    這個函式不需要釋放。你可以用以下方法驗證:unit Unit2;interfaceuses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;type PTT= ^TStringList; TForm2 = class(TForm) Button1: TButton; procedure Button1Click(Sender: TObject); private function StrListFunError(Var AI: PTT):TStringList; function StrListFunRight(Var AI: PTT):TStringList; public end;var Form2: TForm2;implementation{$R *.dfm}procedure TForm2.Button1Click(Sender: TObject);var test:TStringList; tt1:PTT;begin test:=TStringList.Create; try test:=StrListFunError(tt1);//雖然此時未報錯,得所指向的物件已經不正確 ShowMessage(tt1^.Text ); //因為已經被釋放,不能顯示正確值 ShowMessage(test[0]); //出錯,因為在原函式中已經被釋放test:=StrListFunRight(tt1); ShowMessage(tt1^.Text); //test還沒有使用,所以沒有被釋放,可以顯示正確值 ShowMessage(test[0]); ShowMessage(tt1^.Text); //test已經使用,所以被釋放,出現錯誤//結論: //對於TStringList作為函式或者過程的返回值時,在被調函式內不需要釋放 //由編譯器進行自動處理 finally test.Free; end;end;function TForm2.StrListFunError(Var AI:PTT): TStringList;var Re:TStringList;begin //錯誤程式碼 Re:=TStringList.Create; Ai:=@Re; try Re.Add("Error Test; "); Result:=Re; finally Re.Free; end;end;function TForm2.StrListFunRight(var AI: PTT): TStringList;var Re:TStringList;begin //正確程式碼 Re:=TStringList.Create; Ai:=@Re; try Re.Add("Right Test;"); Result:=Re; finally //正確程式碼,不需要釋放,交由編譯器處理 //Re.Free; end;end;end.

  • 中秋節和大豐收的關聯?
  • 小番茄不能和什麼水果一起吃會導致中毒?