2016-01-30 33 views
2

作爲OOP的新手,我很好奇爲什麼Delphi XE7在我嘗試釋放它時使用的日誌記錄類上生成無效指針操作。所以我創建了一個簡單的測試來創建一個對象然後釋放它。我不確定我在這裏丟失了什麼,以及爲什麼當MyObject.Free被調用時拋出這個異常。無效的指針操作釋放對象

在第一個單元中,我創建了這個對象的一個​​實例,如下所示。

unit Unit1; 
interface 
uses 
    Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, 
    Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Unit2; 

type 
    TForm1 = class(TForm) 
    Button1: TButton; 
    Button2: TButton; 
    procedure Button1Click(Sender: TObject); 
    procedure Button2Click(Sender: TObject); 
    private 
    { Private declarations } 
    public 
    { Public declarations } 
    end; 

var 
    Form1: TForm1; 
    MyObject: TMyObject; 

implementation 
{$R *.dfm} 

procedure TForm1.Button1Click(Sender: TObject); 
begin 
    MyObject := TMyObject.Create; 
end; 

procedure TForm1.Button2Click(Sender: TObject); 
begin 
    MyObject.Free; 
end; 

end. 

在第二個單元中,我定義瞭如下對象。

unit Unit2; 
interface 
uses System.Classes; 

    type 
    TMyObject = class 
    public 
    constructor Create; 
    destructor Free; 
    end; 

implementation 

constructor TMyObject.Create; 
begin 
    inherited Create; 
end; 

destructor TMyObject.Free; 
begin 
    inherited Free; 
end; 

end. 

任何幫助表示讚賞。

+3

歡迎來到StackOverflow。你的析構函數應該是標準** Destroy **析構函數的重寫,而不是Free。 – MartynA

回答

5

總是通過重寫名爲Destroy的虛擬析構函數來實現析構函數。

type 
    TMyObject = class 
    public 
    constructor Create; 
    destructor Destroy; override; 
    end; 

constructor TMyObject.Create; 
begin 
    inherited; 
end; 

destructor TMyObject.Destroy; 
begin 
    inherited; 
end; 

摧毀一個實例調用TObject命名Free的方法。這僅在實例不是nil時調用虛擬析構函數Destroy

瞭解從文檔更多:

名稱MyObject較弱。對象用於實例。類用於類。